上的android文本变化监听器 [英] android on Text Change Listener

查看:136
本文介绍了上的android文本变化监听器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一种情况,其中有两个字段。 Field 1和字段2。我所想要的 做的是空场2时字段1被改变,反之亦然。因此,在年底止 一个字段包含的内容就可以了。

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到字段1只,但是当 我做了这两个领域的应用程序崩溃。显然,因为他们试图改变 对方下去。一旦字段1改变它清除字段2在这一刻 字段2被改变,它会清除字段1等等...

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...

有人建议我有什么解决办法吗?我是新来的Java /编程一般 而我真的挣扎在这个小时。

Can someone suggest me any solution? I am new to java/programming in general and Im really struggling for hours on this.

在此先感谢。

推荐答案

您可以添加一个检查,唯一清楚的时候,在字段中的文本不为空(即当长度不是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 这里文档

另外请尊重<一href="http://www.oracle.com/technetwork/java/javase/documentation/$c$cconventions-135099.html#367">naming约定的。

这篇关于上的android文本变化监听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆