Search code examples
androidtextviewandroid-textwatcher

How can I get new entered value on EditText with TextWatcher


I can get the old value. But I do not have a solution to get a new entered value.

In fact, I want to separate the old value from the new value. For example: If oldText=hello and new entered EditText value equal to (hello w or w hello), I want newText=w.

public class MyTextWatcher implements TextWatcher {


    private String oldText = "";
    private String newText = "";

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

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {

    }

}

Thanks for help.


Solution

  • By start andcount parameters in the onTextChanged method, you can calculate and get the new typed value.

    onTextChanged

    This method is called to notify you that, within s, the count characters beginning at start have just replaced old text that had length before. It is an error to attempt to make changes to s from this callback.

    So you can:

    public class MyTextWatcher implements TextWatcher {
    
        private String newTypedString = "";
    
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    
        }
    
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            newTypedString = s.subSequence(start, start + count).toString().trim();
        }
    
        @Override
        public void afterTextChanged(Editable s) {
    
        }
    
    }