androidandroid-studioaddtextchangedlistener

How to access view in addTextChangedListener?


I want to add a method where passing view as parameter below is the code on directly adding somemethod(view) shows error.

abc.addTextChangedListener(new TextWatcher() {
  @Override
  public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

  @Override
  public void onTextChanged(CharSequence s, int start, int before, int count) {
   somemethod(view); // this is where I stuck
  }
 }
}

@Override
public void afterTextChanged(Editable s) {

}
});
.....
somemethod(View view) {}

Solution

  • private class MyTextWatcher implements TextWatcher {
    
        private View view;
    
        private MyTextWatcher(View view) {
            this.view = view;
        }
    
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            //access view
        }
    
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            //access view
        }
    
        @Override
        public void afterTextChanged(Editable s) {
            //access view
        }
    }
    

    Add Listener to View

    editText.addTextChangedListener(new MyTextWatcher(editText));