'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 1:[1]

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) {

    }

}

Solution 2:[2]

Try this code:

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) {
        newText = s.toString().replace(oldText, "").trim();
    }

    @Override
    public void afterTextChanged(Editable s) {

    }

}

Info about text watcher: Differences between TextWatcher 's onTextChanged, beforeTextChanged and afterTextChanged

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 m3esma
Solution 2 Anton Sarmatin