問題描述
我有一個情況,有兩個字段.field1
和 field2
.我所想要的當(dāng) field1
改變時, to do 為空 field2
,反之亦然.所以只在最后一個字段上有內(nèi)容.
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
則效果很好,但是當(dāng)我對應(yīng)用程序崩潰的兩個領(lǐng)域都這樣做.顯然是因為他們試圖改變彼此無限期.一旦 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
的文檔此處.
還請遵守命名約定.
這篇關(guān)于android on Text Change Listener的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!