Home » Android » Set Limit To EditText

Set Limit To EditText

Posted by: admin November 1, 2017 Leave a comment


I want to set a minimum value of in the EditText so the user can’t enter a number less than 50.

<EditText android:id="@+id/number"
                android:hint="(min 50)"
                android:inputType="number" />

Testing when the button is clicked.

You put this into the listener of the button:

if (Integer.valueOf(editText.getText().toString()) < 50) {
    // Do what you want


It’s not problem. InputFilter will help you
you can see it here

Is there a way to define a min and max value for EditText in Android?


I’d suggest you use TextWatcher. Here are simple steps to follow:

STEP 1 – Bring the EditText (or View) that you want to track into Java code

STEP 2 – Implement TextWatcher in your Activity or create a separate class at handles he responsibility of managing text changes (Implementation is similar to other listeners s.a. OnClickListener)

STEP 3 – Implement all the methods inside the TextWatcher (@Override interface methods)

STEP 4 – Use the addTextChangedListener method on the View (EditText) to link it to the TextWatcher (register the view)

STEP 5 – Use one of the available methods to perform the validation

Upon implementation, there will be 3 methods we must override from the interface:

void beforeTextChanged(CharSequence c, int i, int i2, int i3) {}
void onTextChanged(CharSequence c, int i, int i2, int i3) {} 
void afterTextChanged(Editable e) {}

All these three methods are called consequently upon any change (like typing or deleting a letter). It’s enough to use just one of them, and it’s preferable to use the afterTextChanged method. EDITABLE parameter is just a text which we have inside our EditText at the time instant.


you should use InputFilter class

public class InputFilterMinMax implements InputFilter {

private int min, max;

public InputFilterMinMax(int min, int max) {
    this.min = min;
    this.max = max;

public InputFilterMinMax(String min, String max) {
    this.min = Integer.parseInt(min);
    this.max = Integer.parseInt(max);

public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
    try {
        int input = Integer.parseInt(dest.toString() + source.toString());
        if (isInRange(min, max, input))
            return null;
    } catch (NumberFormatException nfe) {
    return "";

private boolean isInRange(int a, int b, int c) {
    return b > a ? c >= a && c <= b : c >= b && c <= a;


You should get a reference of you Edit Text class on your Activity/Fragment

EditText yourEditext = (EditText) findViewById(R.id.editText);

InputFilter[] editFilters = yourEditext.getFilters();
                InputFilter[] newFilters = new InputFilter[editFilters.length + 1];
                System.arraycopy(editFilters, 0, newFilters, 0, editFilters.length);
                newFilters[editFilters.length] = new InputFilterMinMax(0, 59);