gpt4 book ai didi

java - EditText addTextChangedListener 循环

转载 作者:行者123 更新时间:2023-12-02 03:43:06 24 4
gpt4 key购买 nike

我有两个编辑文本,每个都有文本观察器,当第一个 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)));
}
});

最佳答案

您可以在 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);
}

关于java - EditText addTextChangedListener 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36621543/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com