IntentFilter过滤小数点两位

很多时候输入数字都需要实现这样一个需求:最多输入两位小数。
用TextWather监听输入内容虽然可以实现,但是写起来太过麻烦。可以使用InputFilter来实现。

下面说下实现方法:

首先在EditText中设置inputType和digits,控制输入内容。

<EditText
      android:id="@+id/edit_text"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:digits="1234567890."
      android:inputType="numberDecimal"/>

然后在代码中设置接受小数,整数输入:

 KeyListener listener = new DigitsKeyListener(false, true);
 editText.setKeyListener(listener);//保证只能输入一个小数点

最后加上小数点后两位的filter过滤器

InputFilter lengthfilter = new InputFilter() {
        public CharSequence filter(CharSequence source, int start, int end,Spanned dest, int dstart, int dend) {
            if (dest.toString().contains(".")) {
                int pointIndex = dest.toString().indexOf(".");//小数点位置
                String[] array = dest.toString().split("\\.");
                if (array.length == 2) {
                    String lastTwo = dest.toString().split("\\.")[1];//获取小数点后内容
                    if (!TextUtils.isEmpty(lastTwo) && lastTwo.length() >= 2) {//判断是否超过两位
                        if (dstart <= pointIndex) {//判断当前光标是否输入在小数点前
                            return null;//不做过滤操作
                        } else {
                            return "";//返回无内容
                        }
                    }
                }
            }
            return null;
        }
    };
 editText.setFilters(new InputFilter[]{lengthfilter});

OK。搞定!

你可能感兴趣的:(安卓基础组件)