如何撤消对一个edittext的关注并将焦点放在第二个edittext上

时间:2014-11-22 14:08:57

标签: android android-edittext

我想用两个Edittext小部件进行操作,这样我可以先在任何Edittext中写入,也可以在其他Edittext中写入相应的信息。这是我的代码片段: textWatcher1 = new TextWatcher(){

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            s1 = et1.getText().toString();
            if(!s1.equals("")){
                et2.setText(s1);
            } else {
                et2.setText("");
            }
        }

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

        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    };
    textWatcher2 = new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            s1 = et1.getText().toString();
            if(!s1.equals("")){
                et2.setText(s1);
            }else {
                et2.setText("");
            }
        }

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

        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    };
    et1.setOnFocusChangeListener(new OnFocusChangeListener() {

        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if(hasFocus){
                et1.addTextChangedListener(textWatcher1);
                et2.removeTextChangedListener(textWatcher2);
            } else {

            }
        }
    });

    et2.setOnFocusChangeListener(new OnFocusChangeListener() {

        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if(hasFocus){
                et2.addTextChangedListener(textWatcher2);
                et1.removeTextChangedListener(textWatcher1);
            } else {

            }
        }
    });

但问题是它只适用于第一个Edittext,当我想写第二个Edittext然后应用程序崩溃。那么如何解决呢? 提前致谢

1 个答案:

答案 0 :(得分:0)

et1中有et2TextWatcher2混淆了。试试 -

  textWatcher2 = new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            s1 = et2.getText().toString();
            if(!s1.equals("")){
                et1.setText(s1);
            }else {
                et1.setText("");
            }
        }