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
You could take a look at the android.telephony.PhoneNumberFormattingTextWatcher class. It masks a phone number text input with the ###-###-#### pattern.
Try using an
InputFilter
rather than anOnKeyListener
. 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 anOnKeyListener
.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.The easiest way I know to use a mask on EditText in your Android programs in Android Studio is to use
MaskedEditText
library (GitHub link). It's a kind of custom EditText with Watcher that allows you to set a hint with different color (if you want it will be available even when user already started to type), mask and it's very easy to use :-)And that is!
This site gives a good 2 classes that help with masking that I found quite useful.
You need to use the items in the comments to improve it. But worth adding to your program for ease of masking your EditText views for many masks.
you can use this efect in EditText
Use this in an
onKey
function for delicious on-the-fly bunny sex with formatted phone numbers.