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

标签 android textview android-textwatcher

我可以获得旧值。但我没有解决方案来获得新的输入 值(value)。

其实,我想把旧值和新值分开。 例如:如果 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) {

    }

}

感谢您的帮助。

最佳答案

通过onTextChanged方法中的startcount参数,可以计算得到新输入的值。

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.

所以你可以:

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

    }

}

关于android - 如何使用 TextWatcher 在 EditText 上获取新输入的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53864396/

相关文章:

android - 无法在 Android 中授予我的自定义内容提供商权限?

javascript - 有没有办法在phonegap中制作相框应用程序

android - 使 TextView 在 Android 上可滚动

android - 如何在android TextView中使用Get Ordered列表

Android:如果 ListView 中没有项目,显示 TextView 的最佳方式是什么?

android - Android 中的 TextWatcher 警告和慢速类型

java - Android 和 PHP 加密/解密 - 填充问题

android - 在 singleline 为 true 的 TextView 上调用 setmovementmethod 时,文本不可见

android - 在 RecyclerView 的 TextWatcher.onTextChanged() 中使用时,notifyDataSetHasChanged() 会抛出错误

android - 如何在android中的多个编辑文本上添加Text Watcher?