多个 EditText 的 TextWatcher [英] TextWatcher for more than one EditText
问题描述
我想为多个 EditText
字段实现 TextWatcher
接口.目前我正在使用:
I want to implement the TextWatcher
interface for more than one EditText
fields. Currently I am using :
text1.addTextChangedListener(this);
text2.addTextChangedListener(this);
然后覆盖我的活动中的方法:
then overriding the methods in my 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
字段.
However this is working fine but I'm looking for other ways so that I can explicitly identify that in which EditText
field the SoftKeyboard
is currently focused.
推荐答案
@Sebastian Roth 的回答中建议的解决方案不是TextWatcher
的一个实例,用于某些 EditTexts
.对于 n EditTexts
,它是一个类和该类的 n 个实例.
Suggested solution in @Sebastian Roth's answer is not one instance of TextWatcher
for some EditTexts
. It is one class and n instances of that class for n EditTexts
.
每个 EditText 都有自己的 Spannable.TextWatcher
的事件将此 Spannable 作为 s
参数.我检查他们的 hashCode(每个对象的唯一 ID).myEditText1.getText() 返回该 Spannable.因此,如果 myEditText1.getText().hashCode()
等于 s.hashCode()
则意味着 s
属于 myEditText1
Each EditText has its own Spannable. TextWatcher
's events has this Spannable as s
parameter. I check their hashCode (unique Id of each object). myEditText1.getText() returns that Spannable. So if the myEditText1.getText().hashCode()
equals with s.hashCode()
it means that s
belongs to myEditText1
因此,如果您想为某些 EditTexts
设置一个 TextWatcher
实例,您应该使用这个:
So if you want to have one instance of TextWatcher
for some EditTexts
you should use this:
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);
这篇关于多个 EditText 的 TextWatcher的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!