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 some extra string. When I try to do this the program terminates.
final EditText ET = (EditText) findViewById(R.id.editText1);
ET.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count)
{
try
{
ET.setText("***"+ s.toString());
ET.setSelection(s.length());
}
catch(Exception e)
{
Log.v("State", e.getMessage());
}
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after)
{
}
@Override
public void afterTextChanged(Editable s)
{
}
});
My program terminates and even I try to catch the exception like in my code still it terminates. Does anyone have any idea why this happens and how I can achieve this? Thanks.
To supplement Zortkun's answer (where the example code is quite broken), this is how you'd use
afterTextChanged()
to update the sameEditText
:Get familiar with the
Editable
interface to learn about other operations besidesinsert()
.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:late answer, if someone looking this is how i did it.
here is the code.
Here is a snippet that worked for me
where
Utils.getFormattedPhoneNumber()
is your method returning a formatted numberThe content of the
TextView
is uneditable on theonTextChanged
event.Instead, you need to handle the
afterTextChanged
event to be able to make changes to the text.For more thorough explanation see: Android TextWatcher.afterTextChanged vs TextWatcher.onTextChanged
Note: Error
onTextChanged
Obvioulsy, you are causing an endless loop by continuously changing the text on
afterTextChanged
event.From the ref:
Suggestion 1: if you can, check if the
s
is already what you want when the event is triggered.synchronized
method like in this post.Note 2 : Formatting the input as partially hidden with n stars till the last 4 chars ( ****four)
You can use something like this in suggestion 1: