views:

534

answers:

3

Is there a way I can specify an input mask to the EditText control in Android?

I want be able to specify something like ### - ## - #### for a Social Security Number. This will cause any invalid input to be rejected automatically (example, I type alphabetical characters instead of numeric digits).

I realize that I can add an OnKeyListener and manually check for validity. But this is tedious and I will have to handle various edge cases.

Buzzy

+2  A: 

Try using an InputFilter rather than an OnKeyListener. This means you don't have worry about tracking individual key presses and it will also handle things like pasting into a field which would be painful to handle with an OnKeyListener.

You could have a look at the source of the InputFilter implementations that come with Android to give you a starting point for writing your own.

Dave Webb
Thank you. The InputFilter source offers some great insights.
Buzzy
A: 

Buzzy, were you able to use InputFilter to achieve the SSN mask? If possible, can you share thoughts on how you went about it?

Chandra Mohan
A: 

You could take a look at the android.telephony.PhoneNumberFormattingTextWatcher class. It masks a phone number text input with the ###-###-#### pattern.

Fernando Pereira