我有两个输入框(Edit Text Box),在android布局中,我试图通过计算一些值来将一个Edit Text Box的文本设置为另一个Edit Text Box的文本,反之亦然(从第二个Text Box获取文本,然后计算并实时(将其添加到第一个文本框中)(当前在编辑框中键入的时间),我已经看到了“在文本更改侦听器上”的一些答案,并尝试过,但可能是由于关注编辑框的问题而导致崩溃
答案 0 :(得分:0)
同时添加文本观察器可能会导致问题(重复出现效果)。但是您可以一次激活一个文本监视程序来满足您的要求。在更改 edittext1 文本时,我们将删除 edittext2 的文本观察器,并在文本观察器的onTextChanged
中设置 edittext2 edittext1 。那么我们将在 edittext1 的afterTextChanged
文本监视程序中重新激活 edittext2 的文本监视程序。相同的逻辑适用于 edittext1 。
public class MainActivity extends AppCompatActivity {
EditText editText1,editText2,editText3,editText4;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText1=findViewById(R.id.editText1);
editText2=findViewById(R.id.editText2);
editText3=findViewById(R.id.editText3);
editText4=findViewById(R.id.editText4);
editText1.addTextChangedListener(textWatcher1);
editText2.addTextChangedListener(textWatcher2);
editText3.addTextChangedListener(textWatcher3);
editText4.addTextChangedListener(textWatcher4);
}
TextWatcher textWatcher1=new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
editText2.removeTextChangedListener(textWatcher2);
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
editText2.setText(editText1.getText());
}
@Override
public void afterTextChanged(Editable s) {
editText2.addTextChangedListener(textWatcher2);
}
};
TextWatcher textWatcher2=new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
editText1.removeTextChangedListener(textWatcher1);
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
editText1.setText(editText2.getText());
}
@Override
public void afterTextChanged(Editable s) {
editText1.addTextChangedListener(textWatcher1);
}
};
}
TextWatcher textWatcher3=new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
editText4.removeTextChangedListener(textWatcher4);
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
editText4.setText(editText3.getText());
}
@Override
public void afterTextChanged(Editable s) {
editText4.addTextChangedListener(textWatcher4);
}
};
TextWatcher textWatcher4=new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
editText3.removeTextChangedListener(textWatcher3);
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
editText3.setText(editText4.getText());
}
@Override
public void afterTextChanged(Editable s) {
editText3.addTextChangedListener(textWatcher3);
}
};
}