Android Tutorial

Software Setup and Configuration

Android Studio

File Structure

Components

Core Topics

Layout

View

Button

Intent and Intent Filters

Toast

RecyclerView

Fragments

Adapters

Other UI Component

Image Loading Libraries

Date and Time

Material Design

Bars

Working with Google Maps

Chart

Animation

Database

Advance Android

Jetpack

Architecture

App Publish

App Monetization

How to add Mask to an EditText in Android

Adding a mask to an EditText can be useful for various purposes such as formatting phone numbers, credit card numbers, dates, etc. You can utilize TextWatcher or third-party libraries to apply masks to your EditText.

Here's a basic guide to applying a mask using both methods:

1. Using TextWatcher:

This is a simple way without adding any external dependencies:

EditText editText = findViewById(R.id.my_edit_text);
editText.addTextChangedListener(new TextWatcher() {

    private boolean isRunning = false;
    private boolean isDeleting = false;

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        isDeleting = count > after;
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
    }

    @Override
    public void afterTextChanged(Editable s) {
        if (isRunning || isDeleting) {
            return;
        }
        isRunning = true;

        // For instance, apply a mask for a phone number
        String formattedString = s.toString().replaceAll("[^0-9]", "");
        if (formattedString.length() > 3 && formattedString.length() <= 6) {
            formattedString = formattedString.substring(0, 3) + "-" + formattedString.substring(3);
        } else if (formattedString.length() > 6) {
            formattedString = formattedString.substring(0, 3) + "-" + formattedString.substring(3, 6) + "-" + formattedString.substring(6);
        }
        s.replace(0, s.length(), formattedString);

        isRunning = false;
    }
});

2. Using a Third-party Library:

There are libraries specifically designed for masking EditText fields. One of the popular libraries is RedMadRobot's InputMask.

Here's how you can use it:

  • Add Dependency:

    Add the following dependency to your app-level build.gradle:

    implementation 'com.redmadrobot:inputmask:6.x.x' // replace 'x.x' with the latest version
    
  • Set the Mask:

    final MaskedTextChangedListener listener = new MaskedTextChangedListener(
            "+0 ([000]) [000]-[00]-[00]", // mask
            true, // allow to enter only predefined symbols into the edit text
            editText, 
            null, 
            new MaskedTextChangedListener.ValueListener() {
        @Override
        public void onTextChanged(boolean maskFilled, @NonNull final String extractedValue) {
            // handle text change
        }
    }
    );
    
    editText.addTextChangedListener(listener);
    editText.setOnFocusChangeListener(listener);
    editText.setHint(listener.placeholder());
    

With the RedMadRobot's InputMask library, you can set various mask formats very easily.

  1. Implementing input masking in EditText:

    • Description: Implement input masking in EditText to control the format of user input.
    • Code:
      // Example: Masking for phone number (XXX) XXX-XXXX
      editText.addTextChangedListener(new TextWatcher() {
          @Override
          public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
      
          @Override
          public void onTextChanged(CharSequence s, int start, int before, int count) {}
      
          @Override
          public void afterTextChanged(Editable s) {
              String input = s.toString();
              if (input.length() == 3 || input.length() == 7) {
                  editText.append(" ");
              }
          }
      });
      
  2. Using MaskedEditText library for input masking in Android:

    • Description: Utilize third-party libraries like MaskedEditText for easier implementation of input masking.

    • Code:

      // Add the MaskedEditText library dependency in your app-level build.gradle file
      implementation 'com.vicmikhailau:MaskedEditText:2.0.4'
      
      <!-- Replace EditText with MaskedEditText in your layout -->
      <com.vicmikhailau.maskededittext.MaskedEditText
          android:id="@+id/maskedEditText"
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          app:mask="(***) ***-****" />
      
  3. Adding regex-based masks to EditText in Android:

    • Description: Apply regular expression (regex) masks to EditText for more complex and flexible input requirements.
    • Code:
      // Example: Regex-based mask for email input
      String emailRegex = "^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Z|a-z]{2,}$";
      editText.addTextChangedListener(new RegexMaskTextWatcher(emailRegex));