简单来说,是一个类似如下的需求:
两个EditText,假设名字分别是 et1和et2;et1的值*一个数字,假设是4500=et2的值;
当 et1 的值发生变化时,et2 的值也发生变化,et2的值发生变化时,et1的值也发生变化,
用过用简单的 TextWatcher 就会发生死循环,如何避免,下面是这个例子代码的最核心部分,简单来说就是在一个事件起效果时,另外一个事件注销。
private int v1
private EditText et1, et2;
private TextWatcher tw1, tw2;
/** Called when the activity is first created. */
@Override
public void
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
@Override
public void onTextChanged(CharSequence s, int start, int before,int
et2.removeTextChangedListener(tw2);
int
try
et1val =Integer.parseInt(s.toString());
} catch
et1val = 0;
}
Log.i("eee1", ""+et1val);
int et2val = et1val * v1;
et2.setText(""
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,int
}
@Override
public void
et2.addTextChangedListener(tw2);
}
};
tw2 = new
@Override
public void onTextChanged(CharSequence s, int start, int before,int
et1.removeTextChangedListener(tw1);
int
try
et2val = Integer.parseInt(s.toString());
} catch
et2val = 0;
}
Log.i("eee2", ""+et2val);
int et1val = et2val / v1;
et1.setText(""
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,int
}
@Override
public void
et1.addTextChangedListener(tw1);
}
};
et1.addTextChangedListener(tw1);
et2.addTextChangedListener(tw2);
}
标签:et2,et1,int,EditText,void,public,Override,Android,死循环
From: https://blog.51cto.com/u_15588078/6534479