多个编辑文本更改侦听器问题

时间:2015-04-08 15:13:54

标签: android android-edittext changelistener

我有2个edittext字段,我为它们创建了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()方法中添加了监听器吗?

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

在OnCreate方法中添加侦听器,或从xml布局添加提示或设置文本没有任何问题。

确保已将布尔变量声明为实例变量,其默认值为false。

相关问题