Android Edit Text Masking

This blog explains how can you add a mask on your edit text. Currently, Android do not provide any build in function for this masking. However, below are some functions that can be used to achieve this functionality.

Edit Text is a UI element that is used to take input from the user. Many times it is intended to take input from the user in a specific format; e.g. there's a different format for CNIC number, phone number, and credit card number.

Currently, Android does not provide any built-in function for this masking. However, below are some functions that can be used to achieve this functionality.

Functions for Overriding EditText Functionality

  1. @Override  
  2. public void onTextChanged(CharSequence s, int start, int before, int count) {  
  3. }  
  4. @Override  
  5. public void afterTextChanged(Editable s) {  
  6. }  
  7. @Override  
  8. public void beforeTextChanged(CharSequence s, int start, int count, int after) {  
  9. }  

Explanation

Function Name Functionality
onTextChangedThis method is called to notify you that, within s, the count characters beginning at start have just replaced old text that had a length before.
afterTextChangedThis method is called to notify you that, somewhere within s, the text has been changed.
beforeTextChangedThis method is called to notify you that, within s, the count characters beginning at start are about to be replaced by new text with length after.

These functions can be overridden by implementing the TextWatcher interface(Details are available in the link). Write the required masking logic in each function and achieve the required masking. Here is an example project that has overridden the TextWatcher class.

Libraries for EditText Masking

There are many libraries written for this purpose as well. The one written by me can also be found here ( Read me for details on how to integrate it in you Android project). A sample application will soon be uploaded on the PlayStore.

Explanation of Library

onTextChanged function will be called everytime when a new character is added or some character is removed from the data. Check if the user is trying to enter the character at some position which is intended for a masking character. If that's so then append that masking character in the edit text string and place the character entered by the user after that. Similary, you can check for the maximum length and other functionalites as well.

Final Words

Edit Text is an important widget, that is required for input from the user. For restricting or prompting the user to provide input in a specific format masking is important. Therefore, it can be done either by overriding the widget input methods or by using certain libraries available for this purpose.

Feel free to leave a comment in case any help is required and give a thumbs up if you find my blog helpful. Happy coding.