Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save juniorcesarabreu/e5307b41f3e55e314cc782c26f79d4e7 to your computer and use it in GitHub Desktop.
Save juniorcesarabreu/e5307b41f3e55e314cc782c26f79d4e7 to your computer and use it in GitHub Desktop.
TextWatcher for more than one EditText

Each EditText has its own Spannable. TextWatcher's events has this Spannable as s parameter. I check their hashCode (unique Id of each object). myEditText1.getText() returns that Spannable. So if the myEditText1.getText().hashCode() equals with s.hashCode() it means that s belongs to myEditText1

So if you want to have one instance of TextWatcher for some EditTexts you should use this:

private TextWatcher generalTextWatcher = new TextWatcher() {    

    @Override
    public void onTextChanged(CharSequence s, int start, int before,
            int count) {

        if (myEditText1.getText().hashCode() == s.hashCode())
        {
            myEditText1_onTextChanged(s, start, before, count);
        }
        else if (myEditText2.getText().hashCode() == s.hashCode())
        {
            myEditText2_onTextChanged(s, start, before, count);
        }
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count,
            int after) {

        if (myEditText1.getText().hashCode() == s.hashCode())
        {
            myEditText1_beforeTextChanged(s, start, count, after);
        }
        else if (myEditText2.getText().hashCode() == s.hashCode())
        {
            myEditText2_beforeTextChanged(s, start, count, after);
        }
    }

    @Override
    public void afterTextChanged(Editable s) {
        if (myEditText1.getText().hashCode() == s.hashCode())
        {
            myEditText1_afterTextChanged(s);
        }
        else if (myEditText2.getText().hashCode() == s.hashCode())
        {
            myEditText2_afterTextChanged(s);
        }
    }

};

Hash is secure?

Each EditText has its own Spannable. TextWatcher events has this Spannable as CharSequence or Editable parameters. I do not check the Text value of EditTexts. I check their hashCode (unique Id of each object). myEditText1.getText() returns that Spannable not the Text value. So if the myEditText1.getText().hashCode() equals with s.hashCode() means that s belongs to myEditText1

Font: https://stackoverflow.com/a/13787221/7482458

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment