2 EditText + 2 TextWatcher - 计算器错误

2 EditText + 2 TextWatcher - stackoverflow error

我有 2 个 EditText + 2 个 TextWatcher,一个 EditText 影响另一个。 我为此苦苦挣扎,不知道如何避免 Whosebug 错误,

为什么 edit_stezenie_ldl.removeTextChangedListener(watch) 不够?它应该停止这个 TextWatcher。

 @Override
public void onFocusChange(View v, boolean hasFocus) {
     watch = new TextWatcher() {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if( edit_stezenie_ldl.getText().toString().length()==0) {
                edit_stezenie_ldl2.setText(null);
            }
            else {

                String x  = edit_stezenie_ldl.getText().toString();
                Double xy = Double.parseDouble(x) / (36.8);
                Double rounded = round(xy, 2);
                String wynik = rounded.toString();
                edit_stezenie_ldl2.setText(wynik);

            }
        }
        @Override
        public void afterTextChanged(Editable s) {

        }
    };
    watch2 = new TextWatcher(){

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if( edit_stezenie_ldl2.getText().toString().length()==0) {
                edit_stezenie_ldl.setText("");
            }
            else {

                String x  = edit_stezenie_ldl2.getText().toString();
                Double xy = Double.parseDouble(x) / (36.8);
                Double rounded = round(xy, 2);
                String wynik = rounded.toString();
                edit_stezenie_ldl.setText(wynik);
            }
        }
        @Override
        public void afterTextChanged(Editable s) {
        }
    };

    if(v==edit_stezenie_ldl && hasFocus){
             edit_stezenie_ldl2.removeTextChangedListener(watch2);
             edit_stezenie_ldl.addTextChangedListener(watch);
    }
    else if(v==edit_stezenie_ldl2 && hasFocus){

            edit_stezenie_ldl.removeTextChangedListener(watch);
            edit_stezenie_ldl2.addTextChangedListener(watch2);

    }
}

removeTextChangedListener() 不会删除 TextWatcher 因为它与您添加侦听器时的 watch 对象不同,因为您每次重新定义 TextWatcher onFocusChange() 被调用。因此,不会删除任何侦听器,并且在每次焦点更改时,您都会添加新的侦听器,当发生文本更改时,它们会相互调用,并以 WhosebugError 结束。

我建议在 onFocusChange() 之外的某个地方实例化两个 TextWatcher 对象,这样它们只会被创建一次。

或者您只在 null:

时实例化监听器
if (watch == null) {
    watch = new TextWatcher() {
        ...
    };
}
if (watch2 == null) {
    watch2 = new TextWatcher() {
        ...
    };
}