Extension of EditText that enables masking user input.
Define a mask as shown in the example below and the non user input characters will be added automatically.
User input: 123456789
Mask: +(###) ###-###
Mask character: #
_________________________________
Output: +(123) 456-789
Include MaskedEditText
in your layout XML.
<mk.webfactory.dz.maskededittext.MaskedEditText
android:id="@+id/edit_masked_input"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/sample_mask"
android:inputType="text"
android:minWidth="200dp"
app:maskededittext_enforceMaskLength="false"
app:maskededittext_mask="###-###-###"
app:maskededittext_maskCharacter="#"
/>
You can also set the mask programatically.
If enforceMaskLength
is set to true the length of the text does not exceed the length of the mask.
You can extract the raw user input (without the mask) by calling MaskedEditText.getRawInput(): String
See Sample for more details
** For projects that do not use AndroidX use version 1.0
Gradle
implementation 'mk.webfactory.dz:maskededittext:2.0'
Maven
<dependency>
<groupId>mk.webfactory.dz</groupId>
<artifactId>maskededittext</artifactId>
<version>2.0</version>
<type>pom</type>
</dependency>
-
Length input filters
The masking of user input, although correct, doesn't play well withInputFilter.LengthFilter(maxLength)
or in XMLandroid:maxLength="10"
. As a recommendation, usemaskededittext_enforceMaskLength
only. -
Some Input types
Some input types such astextPassword
ortextCapCharacters/Sentences/Words
will be ignored by the MaskedEditText. Others, like numbers, work well though. -
Additional TextWatchers
This component heavily relies on aTextWatcher
to keep the input masked at all times. Adding your own should not cause any problems, but it does - under circumstances, the last change/callback is not reported leaving you poorly updated with the second to last change.
Test this carefully if you want to be updated on the user input real time. SeeR.id.txt_raw_input
in MainActivity of the Sample project for a not so great workaround.
- Mask is set in real time as input changes
- Backspace removes masked characters only (raw user input)
- Adding/removing text works anywhere in the current input
- Enforce mask length trims excess text outside of mask.
4.1.Plays well with InputFilter.LengthFilter Input type is not respected only for non masked characters- Effectively separates raw input from masked input
- Survives configuration changes automatically
- Works on all android versions and devices