我遇到的情况是有两个领域。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,但是当我对两个字段都执行此操作时,应用程序将崩溃。显然是因为它们试图无限期地改变彼此。一旦field1更改,field2此刻 清除就会field2被更改,因此它将清除field1,依此类推…
有人可以提出任何解决方案吗?
你可以添加一个检查以仅在字段中的文本不为空时(即,长度不为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(""); } });