Android

How to set fixed range in EditText input

1. First set EditText input type as number

android:inputType="number"

2. Create a input filter class. that will filter the min to max value.

import android.text.InputFilter;
import android.text.Spanned;

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);
    }

    @Override
    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;
    }
}

3. Now use it like this –

EditText et = (EditText) findViewById(R.id.myEditText);
et.setFilters(new InputFilter[]{ new InputFilterMinMax("1", "12")});

Leave a Reply

Your email address will not be published. Required fields are marked *

July 2020
M T W T F S S
« Apr   Sep »
 12345
6789101112
13141516171819
20212223242526
2728293031  

Site Statistics

  • Users online: 0 
  • Visitors today : 14
  • Page views today : 14
  • Total visitors : 3,982
  • Total page view: 4,457