Search code examples
androidinterfaceandroid-activityandroid-edittexttextwatcher

TextWatcher for more than one EditText


I want to implement the TextWatcher interface for more than one EditText fields. Currently I am using :

text1.addTextChangedListener(this);
text2.addTextChangedListener(this);

then overriding the methods in my Activity:

public void afterTextChanged(Editable s) {}

public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
public void onTextChanged(CharSequence s, int start, int before, int count) 
{
 // do some operation on text of text1 field
 // do some operation on text of text2 field 
}

However this is working fine but I'm looking for other ways so that I can explicitly identify that in which EditText field the SoftKeyboard is currently focused.


Solution

  • Suggested solution in @Sebastian Roth's answer is not one instance of TextWatcher for some EditTexts. It is one class and n instances of that class for n EditTexts.

    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);
            }
        }
    
    };
    

    and

    myEditText1.addTextChangedListener(generalTextWatcher);
    myEditText2.addTextChangedListener(generalTextWatcher);