In my app, the user has to enter a phone number in an EditText
field using the following format:
1(515)555-5555
I don't want the user to type "(", ")", or "-" while entering the number; I want these characters to be added automatically.
For example, suppose the user typed 1
-- the parenthesis after "1" should be added automatically, so that "1(" would be displayed. And I would like to have similar functionality while deleting.
I have tried to set text in the afterTextChanged
method of onTextWatcher
interface, but it is not working; instead it's causing an error. Any help will be greatly appreciated.
You're probably running into a problem because
afterTextChanged
is re-entrant, i.e. changes made to the text cause the method to be called again.If that's the problem, one way way around is to keep an instance variable flag:
As an alternative, you could just use PhoneNumberFormattingTextWatcher -- it doesn't do the formatting that you described, but then again you don't have to do much to use it.
you can try
Check PhoneNumnerFormattingTextWatxher
in case you want your own implementation of TextWatcher then you can use folling appraoch: