I have a situation, where there are two fields. field1
and field2
. All I want
to do is empty field2
when field1
is changed and vice versa. So at the end only
one field has content on it.
field1 = (EditText)findViewById(R.id.field1);
field2 = (EditText)findViewById(R.id.field2);
field1.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {}
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
public void onTextChanged(CharSequence s, int start,
int before, int count) {
field2.setText("");
}
});
field2.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {}
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
public void onTextChanged(CharSequence s, int start,
int before, int count) {
field1.setText("");
}
});
It works fine if I attach addTextChangedListener
to field1
only, but when
I do it for both fields the app crashes. Obviously because they try to change
each other indefinitely. Once field1
changes it clears field2
at this moment
field2
is changed so it will clear field1
and so on...
Can someone suggest any solution?
You can add a check to only clear when the text in the field is not empty (i.e when the length is different than 0).
Documentation for
TextWatcher
here.Also please respect naming conventions.
I know this is old but someone might come across this again someday.
I had a similar problem where I would call setText on a EditText and onTextChanged would be called when I didn't want it to. My first solution was to write some code after calling setText() to undo the damage done by the listener. But that wasn't very elegant. After doing some research and testing I discovered that using getText().clear() clears the text in much the same way as setText(""), but since it isn't setting the text the listener isn't called, so that solved my problem. I switched all my setText("") calls to getText().clear() and I didn't need the bandages anymore, so maybe that will solve your problem too.
Try this:
A bit late of a answer, but here is a reusable solution:
So when the above is used, any
setText()
calls happening within the TextWatcher will not result in the TextWatcher being called again:You can also use the hasFocus() method:
Tested this for a college assignment I was working on to convert temperature scales as the user typed them in. Worked perfectly, and it's way simpler.
check String before set another
EditText
to empty. ifField1
is empty then why need to change again to ( "" )? so you can check the size of Your String with s.lenght() or any other solutionanother way that you can check lenght of String is:
I have also faced the same problem and keep on getting stack full exceptions, and I come with the following solution.
declared initially boolean skipOnChange = false;