Android Edittext 限制输入的最大值和最小值以及小数点值位数

1 首先设置Edittext的输入类型
两种方法:(XML布局)
android:inputType="numberDecimal"
或者

edit.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL|InputType.TYPE_CLASS_NUMBER);

2 重写 InputFilter

  public class InputFilterMinMax implements InputFilter{
            private float min, max;

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

            public InputFilterMinMax(String min, String max) {
                this.min = Float.valueOf(min);
                this.max = Float.valueOf(max);
            }

            @Override
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                try {
                    //限制小数点位数
                    if (source.equals(".") && dest.toString().length() == 0) {
                        return "0.";
                    }
                    if (dest.toString().contains(".")) {
                        int index = dest.toString().indexOf(".");
                        int mlength = dest.toString().substring(index).length();
                        if (mlength == 3) {
                            return "";
                        }
                    }
                    //限制大小
                    float input = Float.valueOf(dest.toString() + source.toString());
                    if (isInRange(min, max, input))
                        return null;
                } catch (Exception nfe) { }
                return "";
            }

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

3 添加监听:

 edit.setFilters(new InputFilter[]{new InputFilterMinMax(0,100)});

你可能感兴趣的:(Android笔记)