设置EditText只能输入固定小数位,并且第一位输入“0”或“.”自动补为“0.”,禁止粘贴内容。

 

    /**
     * 
     * @param editText
     * @param retain 需要保留的小数位
     */
    public static void setInputDecimals(final EditText editText, final int retain) {

        editText.addTextChangedListener(new TextWatcher() {
            public String a = "";
            public boolean isCopy = false;

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

                if (1 == count) {
                    if (0 == start) {
                        a = s.toString();
                        if (".".equals(a)) {
                            s = "0.";
                            a = "0";
                            isCopy = true;
                            editText.setText(s);
                            editText.setSelection(s.length());
                        }
                    } else if (1 == start) {
                        char c = s.charAt(1);
                        if ("0".equals(a) && '.' != (c)) {
                            s = a + "." + c;
                            isCopy = true;
                            editText.setText(s);
                            editText.setSelection(s.length());
                        }
                    }
                    if (s.toString().contains(".")) {
                        if (s.length() - s.toString().indexOf(".") > retain + 1) {
                            s = s.toString().subSequence(0, s.toString().indexOf(".") + retain + 1);
                            isCopy = true;
                            editText.setText(s);
                            editText.setSelection(s.length());
                        }
                    }
                } else if (count > 1) {
                    if (isCopy) {
                        isCopy = false;
                    } else {
                        editText.setText("");
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值