How to get the View in TextWatcher method context?

Paulo Roberto Rosa picture Paulo Roberto Rosa · Apr 4, 2014 · Viewed 8.4k times · Source

I have a handler that is a TextWatcher and i dont know how to get the View that has changed text.

Here is my handler:

TextWatcher handler = new TextWatcher() {

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        // TODO Auto-generated method stub

    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        oldText = s.toString();
    }

    @Override
    public void afterTextChanged(Editable s) {
        //v.setText("afterTextChanged");
    }
};

Note the commented part, that is what i want, to get the View from the EditText that has triggered the event, to change the text after the text was changed.

How i can reach this .setText() method inside the afterTextChanged event? (Like onClick event that view is v)

Answer

Ion Aalbers picture Ion Aalbers · Apr 4, 2014
public static class MyTextWatcher implements TextWatcher {

    private EditText mEditText;

    public MyTextWatcher(EditText editText) {
        mEditText = editText;
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        oldText = mEditText.toString();
    }
    ....
}

Add it with:

    mFirstEditText.addTextChangedListener(new MyTextWatcher(mFirstEditText));