我有2个EditText + 2个TextWatcher,一个EditText影响另一个。
我为此感到困惑,并且不知道如何避免StackOverFlow错误,

为什么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()。因此,永远不会删除任何侦听器,并且在每次焦点更改时都添加一个新的侦听器,当发生文本更改时,它们会互相调用,并以StackOverflowError结尾。

我建议将两个TextWatcher对象实例化到onFocusChange()之外的某个位置,以便仅创建一次。

或者,您仅在监听器为null时实例化监听器:

if (watch == null) {
    watch = new TextWatcher() {
        ...
    };
}
if (watch2 == null) {
    watch2 = new TextWatcher() {
        ...
    };
}

关于android - 2 EditText + 2 TextWatcher-stackoverflow错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34557730/

10-08 20:37