美文网首页Android开发自定义项目
Android EditText 小数输入优化

Android EditText 小数输入优化

作者: afa1332 | 来源:发表于2018-03-13 22:43 被阅读481次

    ———通过EditText输入小数时,可指定整数或小数的位数

    如需下载源码,请访问
    https://github.com/fengchuanfang/DecimalInput

    文章原创,转载请注明出处:
    Android EditText 小数输入优化

    运行效果如下:


    小数输入框演示.gif

    在xml布局文件中,设置EditText的inputType属性为“numberDecimal”,可限制EditText只能输入带小数点的浮点数,如下:

    android:inputType="numberDecimal"
    

    但是,在实际开发应用中,发现只设置这个属性来限制EditText只可输入小数所带来的用户体验并不是很好,无法满足实际应用场景的需求。

    例如以下非正常格式的浮点数也可输入


    非正常格式浮点数.png

    在主流的app中,例如支付宝和微信对以上问题的处理也不是很好,
    例如支付宝充值金额界面,如下;


    支付宝金额非正常输入.png

    首位是“.”时,不具有自动补“0”的逻辑
    微信发红包界面,输入金额时,首位是“.”会自动补“0”,但是不具有自动删除首位无效“0”的逻辑,如下:


    微信红包金额输入首位存在无效0.jpg

    而且在实际应用时,大部分情况需要限制整数或小数的位数,而只通过xml设置EditText的属性并不能很好的实现。

    下面我们通过EditText的addTextChangedListener(TextWatcher watcher)方法,添加一个文本监视器,并结合正则表达式实现以上需求,同事对原始的EditText的外观进行美化。

    写一个小数输入监视类DecimalInputTextWatcher继承自TextWatcher,代码如下:

    public class DecimalInputTextWatcher implements TextWatcher {
        private final EditText mDecimalInputEt;
        private Pattern mPattern;
    
        /**
         * 不限制整数位数和小数位数
         */
        public DecimalInputTextWatcher(EditText decimalInputEt) {
            mDecimalInputEt = decimalInputEt;
        }
    
        /**
         * 限制整数位数或着限制小数位数
         *
         * @param type   限制类型
         * @param number 限制位数
         */
        public DecimalInputTextWatcher(EditText decimalInputEt, Type type, int number) {
            mDecimalInputEt = decimalInputEt;
            if (type == Type.decimal) {
                mPattern = Pattern.compile("^[0-9]+(\\.[0-9]{0," + number + "})?$");
            } else if (type == Type.integer) {
                mPattern = Pattern.compile("^[0-9]{0," + number + "}+(\\.[0-9]{0,})?$");
            }
        }
    
        /**
         * 既限制整数位数又限制小数位数
         *
         * @param integers 整数位数
         * @param decimals 小数位数
         */
    
        public DecimalInputTextWatcher(EditText decimalInputEt, int integers, int decimals) {
            mDecimalInputEt = decimalInputEt;
            mPattern = Pattern.compile("^[0-9]{0," + integers + "}+(\\.[0-9]{0," + decimals + "})?$");
        }
    
    
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    
        }
    
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
    
        }
    
        @Override
        public void afterTextChanged(Editable s) {
            Editable editable = mDecimalInputEt.getText();
            String text = s.toString();
            if (TextUtils.isEmpty(text)) return;
            if ((s.length() > 1) && (s.charAt(0) == '0') && s.charAt(1) != '.') {   //删除首位无效的“0”
                editable.delete(0, 1);
                return;
            }
            if (text.equals(".")) {                                    //首位是“.”自动补“0”
                editable.insert(0, "0");
                return;
            }
            if (mPattern != null && !mPattern.matcher(text).matches() && editable.length() > 0) {
                editable.delete(editable.length() - 1, editable.length());
                return;
            }
            //TODO:可在此处额外添加代码
        }
    
        public enum Type {
            integer, decimal
        }
    }
    
    
    

    在方法afterTextChanged(Editable s)中对于不规范的浮点数输入进行处理,删除首位无效的“0”,以及首位是“.”时,自动补“0”。

    提供三个用于初始化的构造方法,

    1、不限制整数位数和小数位数

    
        /**
         * 不限制整数位数和小数位数
         */
        public DecimalInputTextWatcher(EditText decimalInputEt) {
            mDecimalInputEt = decimalInputEt;
        }
    

    2、限制整数位数或着限制小数位数

        /**
         * 限制整数位数或着限制小数位数
         *
         * @param type   限制类型
         * @param number 限制位数
         */
        public DecimalInputTextWatcher(EditText decimalInputEt, Type type, int number) {
            mDecimalInputEt = decimalInputEt;
            if (type == Type.decimal) {
                mPattern = Pattern.compile("^[0-9]+(\\.[0-9]{0," + number + "})?$");
            } else if (type == Type.integer) {
                mPattern = Pattern.compile("^[0-9]{0," + number + "}+(\\.[0-9]{0,})?$");
            }
        }
    

    3、既限制整数位数又限制小数位数

        /**
         * 既限制整数位数又限制小数位数
         *
         * @param integers 整数位数
         * @param decimals 小数位数
         */
    
        public DecimalInputTextWatcher(EditText decimalInputEt, int integers, int decimals) {
            mDecimalInputEt = decimalInputEt;
            mPattern = Pattern.compile("^[0-9]{0," + integers + "}+(\\.[0-9]{0," + decimals + "})?$");
        }
    

    在Activity中的使用示例如下:

    public class MainActivity extends AppCompatActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            EditText decimalInputEt1 = findViewById(R.id.decimal_input_et1);
            //不限制整数位数和小数位数
            decimalInputEt1.addTextChangedListener(new DecimalInputTextWatcher(decimalInputEt1));
    
            EditText decimalInputEt2 = findViewById(R.id.decimal_input_et2);
            //不限制整数位数,限制小数位数为2位
            decimalInputEt2.addTextChangedListener(new DecimalInputTextWatcher(decimalInputEt2, DecimalInputTextWatcher.Type.decimal, 2));
    
            EditText decimalInputEt3 = findViewById(R.id.decimal_input_et3);
            //限制整数位数为4位,不限制小数位数
            decimalInputEt3.addTextChangedListener(new DecimalInputTextWatcher(decimalInputEt3, DecimalInputTextWatcher.Type.integer, 4));
    
            EditText decimalInputEt4 = findViewById(R.id.decimal_input_et4);
            //限制整数位数为4位,小数位数为2位
            decimalInputEt4.addTextChangedListener(new DecimalInputTextWatcher(decimalInputEt4, 4, 2));
        }
    }
    
    

    同时在xml布局文件中,通过设置EditText的background属性对EditText焦点输入,失去焦点,功能禁用时的外观进行美化

      <EditText
                android:id="@+id/decimal_input_et00"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_margin="10dp"
                android:padding="10dp"
                android:gravity="start"
                android:textSize="14sp"
                android:inputType="numberDecimal"
                android:background="@drawable/input_edit_selector"/>
    

    input_edit_selector.xml的代码为:

    <?xml version="1.0" encoding="utf-8"?>
    <selector xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:state_enabled="false" android:drawable="@drawable/input_disabled_shape"/>
        <item android:state_focused="true" android:drawable="@drawable/input_focused_shape"/>
        <item android:drawable="@drawable/input_normal_shape"/>
    </selector>
    

    input_disabled_shape.xml的代码为:

    <?xml version="1.0" encoding="utf-8"?>
    <shape xmlns:android="http://schemas.android.com/apk/res/android">
        <corners android:radius="4dp"/>
        <stroke android:color="@color/input_disabled_edit" android:width="1dp"/>
        <solid android:color="@color/input_disabled_edit"/>
    </shape>
    

    input_focused_shape.xml的代码为:

    <?xml version="1.0" encoding="utf-8"?>
    <shape xmlns:android="http://schemas.android.com/apk/res/android">
        <corners android:radius="4dp"/>
        <stroke android:color="@color/input_stroke_blue" android:width="1dp"/>
        <solid android:color="@color/input_solid_white"/>
    </shape>
    

    input_normal_shape.xml的代码为:

    <?xml version="1.0" encoding="utf-8"?>
    <shape xmlns:android="http://schemas.android.com/apk/res/android">
        <corners android:radius="4dp"/>
        <stroke android:color="@color/input_stroke_grey" android:width="1dp"/>
        <solid android:color="@color/input_solid_white"/>
    </shape>
    
    

    colors.xml中的各颜色值为:

    <?xml version="1.0" encoding="utf-8"?>
    <resources>
        <color name="input_disabled_edit">#dbdbdb</color>
        <color name="input_stroke_blue">#7393D5</color>
        <color name="input_stroke_grey">#979797</color>
        <color name="input_solid_white">#FFFFFF</color>
    </resources>
    

    运行之后的界面为:


    EditText小数输入优化.png

    相关文章

      网友评论

      本文标题:Android EditText 小数输入优化

      本文链接:https://www.haomeiwen.com/subject/pdztqftx.html