EditText限制输入最大最小值

来源:互联网 发布:php中文网 编辑:程序博客网 时间:2024/05/16 19:09

http://stackoverflow.com/questions/14212518/is-there-a-way-to-define-a-min-and-max-value-for-edittext-in-android

First make this class :

package com.test;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;    }}

Then use this from your Activity :

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

This will allow user to enter values from 1 to 12 only.

EDIT :

Set your edittext with android:inputType="number".

Thanks.


0 0