【问题标题】:Multiple Edit text change listner issue多个编辑文本更改侦听器问题
【发布时间】:2015-04-08 15:13:53
【问题描述】:

我有 2 个编辑文本字段,并为它们创建了 2 个单独的侦听器,如下所示。

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

 email=(EditText)findViewById(R.id.email);
    password=(EditText)findViewById(R.id.password);

    email.addTextChangedListener(new TextWatcher() {

                   public void afterTextChanged(Editable s) {

                       emailFlag=true;
                   }

                   public void beforeTextChanged(CharSequence s, int start,
                     int count, int after) {
                   }

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

                   }
                  });


    password.addTextChangedListener(new TextWatcher() {

                   public void afterTextChanged(Editable s) {
                         passwordFlag=true;
                   }

                   public void beforeTextChanged(CharSequence s, int start,
                     int count, int after) {
                   }

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

                   }
                  });   

    }

现在单击按钮我只想检查更改了哪个文本字段

if(emailFlag){
         System.out.println("Email is changed");
             EditText emailField = (EditText) findViewById(R.id.email);
              userEmailId = emailField.getText().toString();

        }

        if(passwordFlag){
             System.out.println("Password is changed");
             EditText passwordField = (EditText) findViewById(R.id.password);
              userPassword = passwordField.getText().toString();

        }

所以我为每个人设置了单独的标志。

但是在按钮单击时,尽管我已经更改/单击了单个字段,但两个字段的标志值都为真。

任何人都可以帮助我解决这个问题。问题是因为我在 oncreate() 方法中添加了侦听器吗?

【问题讨论】:

  • 您是否在代码中的 editTexts 中设置了文本?如果你这样做,你会触发监听器和 afterTextChanged()。

标签: android android-edittext changelistener


【解决方案1】:

有时我会在视图初始化并被 Android 设置为空时调用 TextWatcher 的方法,因此您可能会得到误报。我建议使用 TextWatcher 中的其他两种方法中的任何一种来验证是否有更改。

【讨论】:

    【解决方案2】:

    在 OnCreate 方法中添加监听器,或者在 xml 布局中添加提示或设置文本都没有错。

    确保您已将布尔变量声明为实例变量,并且它们的默认值为 false。

    【讨论】:

      猜你喜欢
      • 2018-11-08
      • 1970-01-01
      • 2012-06-11
      • 1970-01-01
      • 2018-04-03
      • 2014-03-21
      • 2021-08-30
      • 2020-01-07
      • 1970-01-01
      相关资源
      最近更新 更多