android on Text Change Listener(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
的文档此处.
还请遵守命名约定.
这篇关于android on Text Change Listener的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:android on Text Change Listener
基础教程推荐
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 降序排序:Java Map 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01