我有一种情况,那里有两个领域。 field1
和 field2
。我想做的就是空 field2
当 field1
改变时,反之亦然。所以最后只有一个字段有内容。
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
它工作正常,但是当我为这两个字段执行此操作时,应用程序崩溃。显然是因为他们试图无限期地改变彼此。 Once field1
changes it field2
at this moment field2
is changed so it will clear field1
and so on…
有人可以提出任何解决方案吗?
原文由 inrob 发布,翻译遵循 CC BY-SA 4.0 许可协议
您可以添加一个检查以仅在字段中的文本不为空时(即当长度不为 0 时)清除。
TextWatcher
的文档 在这里。也请尊重 命名约定。