导航

Android,两个互相影响的EditText如何避免死循环

Posted on 2012-08-20 11:00  蝈蝈俊  阅读(2003)  评论(1编辑  收藏  举报

简单来说,是一个类似如下的需求:

两个EditText,假设名字分别是 et1和et2;et1的值*一个数字,假设是4500=et2的值;

当 et1 的值发生变化时,et2 的值也发生变化,et2的值发生变化时,et1的值也发生变化,

用过用简单的 TextWatcher 就会发生死循环,如何避免,下面是这个例子代码的最核心部分,简单来说就是在一个事件起效果时,另外一个事件注销。

private int v1 = 4500;

private EditText et1, et2;

 

private TextWatcher tw1, tw2;

 

/** Called when the activity is first created. */

@Override

public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.main);

 

 

    et1 = (EditText) findViewById(R.id.editText1);

    et2 = (EditText) findViewById(R.id.editText2);

    et1.setText("3");

    et2.setText("13500");

 

    tw1 = new TextWatcher() {

 

    @Override

    public void onTextChanged(CharSequence s, int start, int before,int count) {

        et2.removeTextChangedListener(tw2);

        int et1val = 0;

        try {

            et1val =Integer.parseInt(s.toString());

        } catch (Exception ex) {

            et1val = 0;

        }

        Log.i("eee1", ""+et1val);

 

        int et2val = et1val * v1;

        et2.setText("" + et2val);

    }

 

    @Override

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

        }

 

    @Override

    public void afterTextChanged(Editable s) {

        et2.addTextChangedListener(tw2);

    }

    };


    tw2 = new TextWatcher() {

 

    @Override

    public void onTextChanged(CharSequence s, int start, int before,int count) {

        et1.removeTextChangedListener(tw1);

        int et2val = 0;

        try {

            et2val = Integer.parseInt(s.toString());

        } catch (Exception ex) {

            et2val = 0;

        }

        Log.i("eee2", ""+et2val);

 

 

        int et1val = et2val / v1;

        et1.setText("" + et1val);

    }

 

    @Override

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

    }

 

    @Override

    public void afterTextChanged(Editable s) {

        et1.addTextChangedListener(tw1);

    }

    };

 

    et1.addTextChangedListener(tw1);

    et2.addTextChangedListener(tw2);

 

 

 

}