Android EditText限制小数后两位

一种是笨办法,不推荐使用

mEdit_money.addTextChangedListener(new TextWatcher() {
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        LogU.d("beforeTextChanged=" + s.toString());

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        String money = s.toString();
        if (money.length() > 0) {
            int i = money.indexOf(".");
            int i1 = money.lastIndexOf(".");
            LogU.d("onTextChanged=" + money + ",i=" + i + ",i1=" + i1);
            if (i > 0) {
                String substring = "";
                if (i != i1) {
                    substring = s.toString().substring(0, i1);
                    mEdit_money.setText(substring);
                    mEdit_money.setSelection(substring.length());
                } else if (i == i1 && money.length() - i > 3) {
                    substring = money.substring(0, i + 3);
                    mEdit_money.setText(substring);
                    mEdit_money.setSelection(substring.length());
                }
            } else if (i == 0) {
                mEdit_money.setText("");
            }
        }

    }

    @Override
    public void afterTextChanged(Editable s) {
        LogU.d("afterTextChanged=" + s.toString());
   
    }
});

另一种设置InputFilter,

mEdit_money.setFilters(new InputFilter[]{lendFilter});
/**
 * 设置小数后位数控制
 */
private InputFilter lendFilter = new InputFilter() {
    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
        // 特殊字符(删除)直接返回
        if (TextUtils.isEmpty(source.toString())) {
            return null;
        }
      
        String dValue = dest.toString();
        if (!TextUtils.isEmpty(dValue) && dValue.contains(".") && source.toString().contains(".")) {
//当用户输入@时,输入法可能推送邮箱号等,在这里过滤掉
            return "";
        }
//如果输入的数字在小数点之前,直接通过不处理
        if (dend<=dValue.indexOf(".")){
         return null;
        }
        String[] splitArray = dValue.split("\\."); //拆分小数点
        if (splitArray.length > 1) {
            String dotValue = splitArray[1];
            int diff = dotValue.length() + 1 - 2;//2表示输入框的小数位数
      
            if (diff > 0) {
                if (source.toString().length() > 1) {
                    return "";
                } else {
                    return source.subSequence(start, end - diff);
                }
            }
        }
        return null;
    }
};

你可能感兴趣的:(不用找系列,android,android-studio,android,studio)