android - TextWatcher 用于多个 EditText

标签 android interface android-activity android-edittext textwatcher

我想为多个EditText 字段实现TextWatcher 接口(interface)。目前我正在使用:

text1.addTextChangedListener(this);
text2.addTextChangedListener(this);

然后覆盖我的 Activity 中的方法:

public void afterTextChanged(Editable s) {}

public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
public void onTextChanged(CharSequence s, int start, int before, int count) 
{
 // do some operation on text of text1 field
 // do some operation on text of text2 field 
}

但是这工作正常,但我正在寻找其他方法,以便我可以明确识别 SoftKeyboard 当前关注的 EditText 字段。

最佳答案

@Sebastian Roth's answer 中的建议解决方案对于某些 EditTexts,它不是 TextWatcher 的一个实例。对于 n EditTexts,它是一个类和该类的 n 个实例。

每个 EditText 都有自己的 Spannable。 TextWatcher 的事件有这个 Spannable 作为 s 参数。我检查他们的 hashCode (每个对象的唯一 ID)。 myEditText1.getText() 返回 Spannable。因此,如果 myEditText1.getText().hashCode() 等于 s.hashCode() 这意味着 s 属于 myEditText1

因此,如果您想为某些 EditTexts 提供一个 TextWatcher 实例,您应该使用这个:

private TextWatcher generalTextWatcher = new TextWatcher() {    

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

        if (myEditText1.getText().hashCode() == s.hashCode())
        {
            myEditText1_onTextChanged(s, start, before, count);
        }
        else if (myEditText2.getText().hashCode() == s.hashCode())
        {
            myEditText2_onTextChanged(s, start, before, count);
        }
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count,
            int after) {

        if (myEditText1.getText().hashCode() == s.hashCode())
        {
            myEditText1_beforeTextChanged(s, start, count, after);
        }
        else if (myEditText2.getText().hashCode() == s.hashCode())
        {
            myEditText2_beforeTextChanged(s, start, count, after);
        }
    }

    @Override
    public void afterTextChanged(Editable s) {
        if (myEditText1.getText().hashCode() == s.hashCode())
        {
            myEditText1_afterTextChanged(s);
        }
        else if (myEditText2.getText().hashCode() == s.hashCode())
        {
            myEditText2_afterTextChanged(s);
        }
    }

};

myEditText1.addTextChangedListener(generalTextWatcher);
myEditText2.addTextChangedListener(generalTextWatcher);

关于android - TextWatcher 用于多个 EditText,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4283062/

相关文章:

android - 是否可以通过 Intent.ACTION_SEND 检索和存储用户选择共享文件

java - 想要一个简单的代码来获取州名称和城市名称取决于选择

Android App create directory 适用于大多数,但在许多情况下会出现 unable to create directory on sdcard

Android:作为市场应用程序的本地服务?

python - 如何最好地根据配置指定要使用的接口(interface)子类

java - 在列表中显示数据时出现问题

android - 在 Android 中预加载网页(使用 WebView?)

android - 一个好的 Android 应用程序设计(初学者/新手级别)的重要注意事项?

c# - 强制派生类实现接口(interface)

delphi - 多个接口(interface),Supports() 函数和引用计数