我有两个编辑文本,每一个都有文本观察器,当第一个edittext文本被更改时,它会更改第二个edittext文本,似乎代码创建了一个循环,有什么我可以做的让文本观察者只听用户输入,而不是通过代码更改文本?
et1.addTextChangedListener(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) {
}
@Override
public void afterTextChanged(Editable s) {
double x = Double.valueOf(et1.getText().toString());
et2.setText(String.valueOf((x*2)));
}
});
et2.addTextChangedListener(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) {
}
@Override
public void afterTextChanged(Editable s) {
double x = Double.valueOf(et2.getText().toString());
et1.setText(String.valueOf((x/2)));
}
});
答案 0 :(得分:2)
您可以在TextWatcher
上保留一个引用,以便在操作之前将其删除,然后再将它们放回去。
private TextWatcher tv1;
private TextWatcher tv2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText et1 = (EditText) findViewById(R.id.editText);
final EditText et2 = (EditText) findViewById(R.id.editText1);
tv1 = 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) {}
@Override
public void afterTextChanged(Editable s) {
double x = Double.valueOf(et1.getText().toString());
et2.removeTextChangedListener(tv2); // "disable" the watcher
et2.setText(String.valueOf((x*2)));
et2.addTextChangedListener(tv2); // "enable" the watcher
}
};
tv2 = 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) {}
@Override
public void afterTextChanged(Editable s) {
double x = Double.valueOf(et2.getText().toString());
et1.removeTextChangedListener(tv1); // "disable" the watcher
et1.setText(String.valueOf((x/2)));
et1.addTextChangedListener(tv1); // "enable" the watcher
}
};
et1.addTextChangedListener(tv1);
et2.addTextChangedListener(tv2);
}