Masks in Android's Edit Text fields

You don't need to create a custom EditText view class to add masks in Android EditText fields.

This solution just uses a TextWatcher to get things done, without any additional libraries.

Create the following class in your project :)

Add the text watcher to your edit text field!

In you can put in you activity onCreate

EditText phoneNumber = (EditText) findViewById(R.id.phoneNumber)
phoneNumber.addTextChangedListener(new MaskWatcher("####-####"));

And this is it!

With Android Data Binding

Add the textChangedListener in your layout xml file

<EditText
android:id="@+id/phoneNumber"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="number|text"
android:text="@={binder.phoneNumber}"
android:maxLength="9"
android:addTextChangedListener="@{binder.phoneNumberWatcher}"
android:maxLines="1"/>

In your data object, in this case named Binder.java

public class Binder {
public TextWatcher phoneNumberWatcher = new MaskWatcher("####-####");
}

Extra

I also added a CPF* mask as a builder method so if you need for CPF* instead of creating a instance for it.
*CPF is a Brazilian document

MaskWatcher.buildCpf()

I advise you to do the same for your most used cases or even better create a separate builder class. Try anything you can do to avoid defining the same masks over and over again.