Replace character inside TextWatcher in android

I use TextWatcher to change the value of the pressed key. my goal is to replace some characters while typing. for example, when I type keys, if the character "S" is reached, replace it with the character "a". my question is: should I do this in beforeTextChanged ?? as? can anyone give me an example?

+4
source share
3 answers

Using beforeTextChanged will not be useful, because it will not interrupt the actual key print in EditText. I would use something similar to:

public void afterTextChanged(Editable s) { if(s.length() > 0 && s.toString().charAt(s.length()-1) == 'S') { final String newText = s.toString().substring(0, s.length()-1) + "a"; editText.setText(newText); } } 

I added some toString (), not 100% sure that Editable works, but I think it should cover it.

+1
source

I know this post is a couple of years, but both versions did not work for me and created a hybrid between the two answers.

 @Override public void afterTextChanged(Editable editable) { if (editable.toString().contains(",")) { Editable ab = new SpannableStringBuilder(editable.toString().replace(",", "")); editable.replace(0, editable.length(), ab); } } 
+7
source
 @Override public void afterTextChanged(Editable arg0) { Editable ab = new SpannableStringBuilder(arg0.toString().replace("S", "a")); arg0 = ab ; } 
-1
source

All Articles