Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I avoid execution of onTextChanged in Android's EditText

How can I avoid that a code line like:

((EditText) findViewById(R.id.MyEditText)).setText("Hello"); 

Will cause an event here:

((EditText) findViewById(R.id.MyEditText)).addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start,     int before, int count) { // HERE }  @Override public void beforeTextChanged(CharSequence s, int start,     int count, int after) { }  @Override public void afterTextChanged(Editable s) { } }); 

I want to know if there is any way to inhibit the execution of onTextChanged as I noticed in the case of selecting a AutoCompleteTextView's dropdown result (no onTextChanged is executed!).

I'm not seeking for workarounds like "if hello do nothing"...

like image 469
wildnove Avatar asked Oct 09 '12 14:10

wildnove


2 Answers

The Source for AutoCompleteTextView shows that they set a boolean to say the text is being replaced by the block completion

         mBlockCompletion = true;          replaceText(convertSelectionToString(selectedItem));          mBlockCompletion = false;     

This is as good a way as any to achieve what you want to do. The TextWatcher then checks to to see if the setText has come via a completion and returns out of the method

 void doBeforeTextChanged() {      if (mBlockCompletion) return; 

Adding and removing the TextWatcher will be more time consuming for the application

like image 89
Dazzy_G Avatar answered Oct 17 '22 07:10

Dazzy_G


You can check which View has the focus currently to distinguish between user and program triggered events.

EditText myEditText = (EditText) findViewById(R.id.myEditText);  myEditText.addTextChangedListener(new TextWatcher() {     @Override     public void onTextChanged(CharSequence s, int start, int before, int count) {          if(myEditText.hasFocus()) {             // is only executed if the EditText was directly changed by the user         }     }      //... }); 

Take a look here for a more detailled version of that answer.

like image 23
Willi Mentzel Avatar answered Oct 17 '22 07:10

Willi Mentzel