2 EditText + 2 TextWatcher - stackoverflow错误

时间:2016-01-01 16:13:19

标签: android android-edittext stack-overflow textwatcher

我有2个EditText + 2个TextWatcher,一个EditText影响另一个。 我很挣扎,并且不知道如何避免StackOverFlow错误,

为什么edit_stezenie_ldl.removeTextChangedListener(手表)还不行?它应该停止这个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);

    }
}

1 个答案:

答案 0 :(得分:1)

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

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

或者,您只能在onFocusChange()

时实例化侦听器
null