i use a TextWatcher to change pressed key value. my goal is that replace some characters while typing. for example when i type keys, if reached "S" character, replaces it with "a" character. my question is: should i do it in beforeTextChanged?? how? can anyone give me an example?
I know that this post is a couple of years old, but both versions did not work for me and have build 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);
}
}
Using beforeTextChanged won't be useful because it won't interrupt the actual printing of the key to the 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()'s, not 100% sure how Editable works but I think that should cover it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With