In my Android application I need to implement a TextWatcher interface to implement onTextChanged. The problem I have is, I want to update the same EditText With
To supplement Zortkun's answer (where the example code is quite broken), this is how you'd use afterTextChanged() to update the same EditText:
editText.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 editable) {
if (!editable.toString().startsWith("***")) {
editable.insert(0, "***");
}
}
});
Get familiar with the Editable interface to learn about other operations besides insert().
Note that it's easy to end up in an infinite loop (the changes you do trigger afterTextChanged() again), so typically you'd do your changes inside an if condition, as above.
As afterTextChanged() javadocs say:
It is legitimate to make further changes to s from this callback, but be careful not to get yourself into an infinite loop, because any changes you make will cause this method to be called again recursively.