I am trying to make two EditText where I type anything in one of the EditText, the text I typed will be shown on the other EditText.
private EditText input_a;
private EditText input_b;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
input_a = (EditText) findViewById(R.id.input_a);
input_b = (EditText) findViewById(R.id.input_b);
input_a.setOnFocusChangeListener(this);
input_b.setOnFocusChangeListener(this);
}
@Override
public void onFocusChange(View v,boolean hasFocus) {
// TODO Auto-generated method stub
if(v==input_a && hasFocus){
input_a.setText("");
input_b.setText("");
input_a.addTextChangedListener(new TextWatcher(){
@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
input_b.setText(input_a.getText());
}
@Override
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
// TODO Auto-generated method stub
}
@Override
public void onTextChanged(CharSequence s, int start,
int before, int count) {
// TODO Auto-generated method stub
}
});
}else if(v==input_b && hasFocus){
input_b.setText("");
input_a.setText("");
input_b.addTextChangedListener(new TextWatcher(){
@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
input_a.setText(input_b.getText());
}
@Override
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
// TODO Auto-generated method stub
}
@Override
public void onTextChanged(CharSequence s, int start,
int before, int count) {
// TODO Auto-generated method stub
}
});
}
So when I type in the input_a, it works fine, the text I input is shown in input_b, however, when I type in the input_b, the application close unexpectedly. I don’t see why the two blocks of codes are really similar but only one of them works.
You are probably getting a stack overflow (ironic isn’t it)?
The problem is that when input_a gets focus, you are adding a TextChangedListener and in that listener you set the contents for input_b. This works just fine.
However, when focus changes to input_b, you add a TextChangedListener to input_b but you still have the TextChangedListener for input_a as well. Now when you type into input_b it changes the contents of input_a which triggers its TextChangeListener which changes the contents of input_b. This triggers the TextChangedListener for input_b and you just continue this cycle.