如何使用TextWatcher在EditText上获取新输入的值

时间:2018-12-20 07:47:30

标签: android textview android-textwatcher

我可以得到旧的价值。但是我没有办法输入新的 值。

事实上,我想将旧值与新值分开。 例如:如果oldText=hello并且新输入的EditText值等于(hello ww hello),则我想要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) {

    }

}

感谢帮助。

2 个答案:

答案 0 :(得分:2)

尝试以下代码:

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

    }

}

有关文本监视程序的信息: Differences between TextWatcher 's onTextChanged, beforeTextChanged and afterTextChanged

答案 1 :(得分:1)

通过start方法中的countonTextChanged参数,您可以计算并获取新的类型化值。

onTextChanged

  

调用此方法是为了通知您s内的count   以start开头的字符刚刚替换了具有   长度before。尝试从中更改s是错误的   此回调。

因此您可以:

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

    }

}