Search code examples
javaandroidandroid-edittextfreezeandroid-textinputedittext

Android EditText app freezes on calling clear inside TextWatcher


My app is freezing on calling clear onTextChanged TextWatcher

Following is my code

        materialEditText.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) {
            if(s.toString().equals("$")){
                materialEditText.getText().clear();
         
            }
            else if(!s.toString().contains("$")){
                materialEditText.setText("$"+s);
                Selection.setSelection(materialEditText.getText(), materialEditText.getText().length());

            }
        }

Following line is causing freeze how to fix this?

 materialEditText.getText().clear();

Solution

  • Calling setText() in onTextChanged() of an editText will cause infinite loop. You need to do a workaround to setText() by either using flag or some any other means. Update text only if not updated. So that it don't go into infinite loop