android on Text Change Listener
我有一个情况,有两个字段.field1
和 field2
.我所想要的当 field1
改变时, to do 为空 field2
,反之亦然.所以只在最后一个字段上有内容.
I have a situation, where there are two fields. field1
and field2
. All I want
to do is empty field2
when field1
is changed and vice versa. So at the end only
one field has content on it.
field1 = (EditText)findViewById(R.id.field1);
field2 = (EditText)findViewById(R.id.field2);
field1.addTextChangedListener(new TextWatcher() {
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) {
field2.setText("");
}
});
field2.addTextChangedListener(new TextWatcher() {
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) {
field1.setText("");
}
});
如果我仅将 addTextChangedListener
附加到 field1
则效果很好,但是当我对应用程序崩溃的两个领域都这样做.显然是因为他们试图改变彼此无限期.一旦 field1
更改,此时它会清除 field2
field2
已更改,因此它将清除 field1
等等...
It works fine if I attach addTextChangedListener
to field1
only, but when
I do it for both fields the app crashes. Obviously because they try to change
each other indefinitely. Once field1
changes it clears field2
at this moment
field2
is changed so it will clear field1
and so on...
有人可以提出任何解决方案吗?
Can someone suggest any solution?
推荐答案
您可以添加一个检查以仅在字段中的文本不为空时(即长度不为0时)清除.
You can add a check to only clear when the text in the field is not empty (i.e when the length is different than 0).
field1.addTextChangedListener(new TextWatcher() {
@Override
public void afterTextChanged(Editable s) {}
@Override
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start,
int before, int count) {
if(s.length() != 0)
field2.setText("");
}
});
field2.addTextChangedListener(new TextWatcher() {
@Override
public void afterTextChanged(Editable s) {}
@Override
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start,
int before, int count) {
if(s.length() != 0)
field1.setText("");
}
});
TextWatcher
的文档此处.
还请遵守命名约定.
相关文章