Search code examples
androidtextwatcheraddtextchangedlistener

Avoiding backspace in EditText afterTextChanged() method


So, I have implemented a simple replace method that replaces a character just before where the text is changed.

 @Override
 public void afterTextChanged(Editable s) {

     editText.removeTextChangedListener(this);

     if (s.length() == 0)
       return;
       s.replace(editText.getSelectionStart(),editText.getSelectionStart()+1,"PP");

     editText.addTextChangedListener(this);
}

Since this is effective for all kind of text change, It adds the "PP" even I press the back space button. Is there any way to exclude backspace from this?


Solution

  • First detect Backspace pressed or not

    then avoid your replace when backspace pressed

    editText.addTextChangedListener(new TextWatcher() {
    
            //Normally assume that Backspace not pressed 
            boolean isNotBackspace = true;
    
            @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 current count is grater then before that means char added
                //So if current count is smaller then before that means backspace pressed 
                isNotBackspace = count>before;
            }
    
            @Override
            public void afterTextChanged(Editable s) {
    
                editText.removeTextChangedListener(this);
                Log.e("isNotBackButton", isNotBackButton+"");
    
                if (s.length() == 0) {
                    //Edit is here 
                    //return; //need to block return; because this preventing
                    //from adding  adding addTextChangedListener
                    isNotBackButton = true;
                //if not backspace pressed then proceed else no action 
                }else if(isNotBackButton){
                    s.replace(editText.getSelectionStart(), editText.getSelectionEnd(), "PP");
                }
    
                editText.addTextChangedListener(this);
    
            }
     });