-2

i want to replace typed character with "a" charcter in Android's TextWatcher but save real typed character inside a variable too. to do this, in afterTextChanged i write this code to replace character:

if(s.toString().charAt(s.length()-1) != 'a'){                               
 txtfreak.setText(s.toString().substring(0, s.length()-1) + "a"); 
 txtfreak.setSelection(txtfreak.getText().length());
}

and i want that before replacing, save the real typed character, and to do this, in beforeTextChanged i write this code:

freaktext=s.toString();

but id doesnt work and freaktext contains changes that i made in afterTextChanged!! my question is that beforeTextChanged runs before than afterTextChanged? in my code it seems its not!!

Fcoder
  • 9,066
  • 17
  • 63
  • 100

2 Answers2

1

There is an alternate method to using a TextWatcher to achieve what you want, that may work in your situation. The method below will allow you to display 'a' in place of every character and access the original text in the EditText field.

I hope it works for you instead of TextWatcher.

Warning: If the method below will not server your purposes, then it is certainly possible with TextWatcher as you have started, but even after you fix your bug you will have to go much further. You will have to manually handle users who edit the text in any way possible, including from the beginning or middle of the Span or with Paste from the clipboard.


You need a combination of android:inputType="textPassword" (which changes all of the text to a dot ".") and implement PasswordTransformationMethod (to change the default dot to an 'a').

You will setup your freaktext variable like this:

freaktext.setTransformationMethod(new MyPasswordTransformationMethod());

You will have to visit this link kudos to @Eric for the complete example: In android how to show asterisk (*) in place of dots in EditText having inputtype as textPassword?

Community
  • 1
  • 1
David Manpearl
  • 12,362
  • 8
  • 55
  • 72
1
if(s.toString().charAt(s.length()-1) != 'a'){
freaktext=txtfreak.getText().toString();                               
 txtfreak.setText(s.toString().substring(0, s.length()-1) + "a"); 
 txtfreak.setSelection(txtfreak.getText().length());
}
Hoan Nguyen
  • 18,033
  • 3
  • 50
  • 54