Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replace character inside TextWatcher in android

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?

like image 897
Fcoder Avatar asked Mar 27 '13 07:03

Fcoder


2 Answers

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);
    }
}
like image 187
quantum apps Avatar answered Oct 25 '22 09:10

quantum apps


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.

like image 27
RyPope Avatar answered Oct 25 '22 10:10

RyPope