android 上的文本更改侦听器 [英] android on Text Change Listener
问题描述
我有一个情况,有两个字段.field1
和 field2
.我所想要的当 field1
改变时,要做的是空 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
的文档此处.
还请遵守命名约定.
这篇关于android 上的文本更改侦听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!