监听多个EditText,只有当它们都有输入后,相应Button才能被点击

这篇文章是网上的资源。

public class SomeMonitorEditText implements TextWatcher {

   private Button button;
   private EditText[] text;

   public void SetMonitorEditText(final Button button, final EditText... text) {

      this.button = button;
      this.text = text;


      for (int i = 0; i < text.length; i++) {

         if (text[i] != null) {

            text[i].addTextChangedListener(SomeMonitorEditText.this);
         }

      }
   }

   @Override
   public void beforeTextChanged(CharSequence s, int start, int count,
         int after) {
      // TODO Auto-generated method stub

   }
   @Override
   public void onTextChanged(CharSequence s, int start, int before, int count) {

   }

   @Override
   public void afterTextChanged(Editable s) {
      // TODO Auto-generated method stub
      for (int i = 0; i < text.length; i++) {

         if (text[i].length() == 0) {
            button.setBackgroundResource(R.drawable.graylong_btn);
            button.setEnabled(false);
            return;//这句代码值两千万
         } else {

            button.setBackgroundResource(R.drawable.red_btn);
            button.setEnabled(true);

         }
      }
   }

}

主函数的布局文件就不写了,见图片
这里写图片描述

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        EditText et1 = (EditText) findViewById(R.id.et1);
        EditText et2 = (EditText) findViewById(R.id.et2);
        EditText et3 = (EditText) findViewById(R.id.et3);
        EditText et4 = (EditText) findViewById(R.id.et4);
        Button btn = (Button) findViewById(R.id.btn);

        new SomeMonitorEditText().SetMonitorEditText(btn, et1, et2, et3, et4);

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(MainActivity.this, "被点击了", Toast.LENGTH_SHORT).show();
            }
        });

    }

}
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值