删除焦点时removeTextChangedListener

时间:2017-11-23 15:55:22

标签: java android

我在方法内部的EditText中调用 onFocusChange 方法,当该字段具有焦点时,我将 addTextChangedListener 与先前声明的 TextWatcher <调用/ em>到同一个字段。 当该字段失去焦点时,我删除 TextWatcher 。 但它看起来不起作用,因为在第二个字段中,我最终需要将文本设置为第一个字段,最后调用我之前删除的 TextWatcher

    et1.setOnFocusChangeListener(new View.OnFocusChangeListener() {

        @Override
        public void onFocusChange(View v, boolean hasFocus) {

            final TextWatcher watcher = new TextWatcher() {

                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                    // Do things
                }

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

                @Override
                public void afterTextChanged(Editable s) {
                    // Do things
                }
            };

            if (hasFocus) {
                et1.addTextChangedListener(watcher);
            } else {
                et1.removeTextChangedListener(watcher);
            }
        }

然后在这里启动第二个字段的代码(使用类似的逻辑)

    et2.setOnFocusChangeListener(new View.OnFocusChangeListener() {

        @Override
        public void onFocusChange(View v, boolean hasFocus) {

            final TextWatcher watcherEt2 = new TextWatcher() {

                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                    // Do things
                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                    // Do things
                   et1.setText("from things"); //here the removed TextWatcher is runned
                }

                @Override
                public void afterTextChanged(Editable s) {
                    // Do things
                }
            };

            if (hasFocus) {
                et2.addTextChangedListener(watcherEt2);
            } else {
                et2.removeTextChangedListener(watcherEt2);
            }
        }

这是一个Android Studio错误,或者我想念一些东西?

1 个答案:

答案 0 :(得分:1)

首先,我建议您不要在textWatcher方法中创建onFocusChange,因为在调用onFocusChange时不断创建它并不重要, 然后我想问你为什么要删除textWatchers,因为如果你的EditText没有关注它,那么textWatcher将无效/ p>