Masked Input Using EditText Widget in Android
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.
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 :-)
compile 'ru.egslava:MaskedEditText:1.0.5'
<br.com.sapereaude.maskedEditText.MaskedEditText
android:id="@+id/phone_input"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="phone"
android:typeface="monospace"
mask:allowed_chars="1234567"
mask:mask="###-##-##"
app:keep_hint="true"
/>
And that is!