android EditText输入框输入金额保留两位小数点

使用环境: 

               输入框输入金额,需要处理首字符不能是小数点, 输入金额只保存小数点往后两位数字

使用方法:

       binding.money.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL | InputType.TYPE_CLASS_NUMBER);
        binding.money.setFilters(new InputFilter[]{new InputFilter() {
            @Override
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                if (source.equals(".") && dest.toString().length() == 0) {
                    return "0.";
                }
                if (dest.toString().contains(".")) {
                    int index = dest.toString().indexOf(".");
                    int length = dest.toString().substring(index).length();
                    if (length == 3) {
                        return "";
                    }
                }
                return null;
            }
        }});

        binding.money.addTextChangedListener(new TextWatcher() {
            @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 (TextUtils.isEmpty(s)) {
                    return;
                }
                if (s.length() == 1 && s.toString().equals(".")) {
                    binding.money.setText("");
                    return;
                }
                int counter = counter(s.toString(), '.');
                if (counter > 1) {
                    int index = s.toString().indexOf('.');
                    binding.money.setText(s.subSequence(0, index + 1));
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

猜你喜欢

转载自blog.csdn.net/csdn_loveQingQing/article/details/85275328