android on Text Change Listener

时间:2023-01-14
本文介绍了android on Text Change Listener的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个情况,有两个字段.field1field2.我所想要的当 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 更改,此时它会清除 field2field2 已更改,因此它将清除 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!

上一篇:向 JNA Class Java (Kernel32) 添加另一种方法 下一篇:Android中的分页文本

相关文章

最新文章