如何将EditText长度限制为7个整数和2个小数位?

ara*_*ind 15 android android-layout android-edittext

我有一个EditText盒子,必须允许用户输入最多7个数字和两个小数位.输入七位数后,不应再允许添加一位数,但我可能允许最多2位小数.我使用十进制过滤器2位小数,这个代码用XML

android:maxLength="7"    
android:imeOptions="actionDone"                  
android:inputType="numberDecimal"
Run Code Online (Sandbox Code Playgroud)

EditText允许enter8位数.怎么解决这个问题?

小智 25

在onCreate下试试这个

 youreditText.setFilters(new InputFilter[] {new DecimalDigitsInputFilter(5,1)});
Run Code Online (Sandbox Code Playgroud)

在你的程序中的任何地方

   public class DecimalDigitsInputFilter implements InputFilter {

        Pattern mPattern;

        public DecimalDigitsInputFilter(int digitsBeforeZero,int digitsAfterZero) {
            mPattern=Pattern.compile("[0-9]{0," + (digitsBeforeZero-1) + "}+((\\.[0-9]{0," + (digitsAfterZero-1) + "})?)||(\\.)?");
        }

        @Override
        public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {

                Matcher matcher=mPattern.matcher(dest);       
                if(!matcher.matches())
                    return "";
                return null;
            }

        }
Run Code Online (Sandbox Code Playgroud)

  • 这个解决方案有效,但是当您尝试再次编辑输入的值时,它将不允许您在小数点之前重新输入任何内容,直到您清除所有内容,因此@Taras Smakula的答案更正确 (2认同)

小智 11

您可以使用此输入过滤器来解决您的问题. 要设置过滤器:

mEditText.setFilters(new InputFilter[]{new DigitsInputFilter(maxDigitsBeforeDot, maxDigitsAfterDot, maxValue)});
Run Code Online (Sandbox Code Playgroud)

如果你不希望前或小数点后限制数字只是把Integer.MAX_VALUE,以禁用最大值限制使用Double.POSITIVE_INFINITY.

您可以将此过滤器用于输入数字或数字和文本的文本字段.

public class DigitsInputFilter implements InputFilter {

    private final String DOT = ".";

    private int mMaxIntegerDigitsLength;
    private int mMaxDigitsAfterLength;
    private double mMax;


    public DigitsInputFilter(int maxDigitsBeforeDot, int maxDigitsAfterDot, double maxValue) {
        mMaxIntegerDigitsLength = maxDigitsBeforeDot;
        mMaxDigitsAfterLength = maxDigitsAfterDot;
        mMax = maxValue;
    }

    @Override
    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
        String allText = getAllText(source, dest, dstart);
        String onlyDigitsText = getOnlyDigitsPart(allText);

        if (allText.isEmpty()) {
            return null;
        } else {
            double enteredValue;
            try {
                enteredValue = Double.parseDouble(onlyDigitsText);
            } catch (NumberFormatException e) {
                return "";
            }
            return checkMaxValueRule(enteredValue, onlyDigitsText);
        }
    }


    private CharSequence checkMaxValueRule(double enteredValue, String onlyDigitsText) {
        if (enteredValue > mMax) {
            return "";
        } else {
            return handleInputRules(onlyDigitsText);
        }
    }

    private CharSequence handleInputRules(String onlyDigitsText) {
        if (isDecimalDigit(onlyDigitsText)) {
            return checkRuleForDecimalDigits(onlyDigitsText);
        } else {
            return checkRuleForIntegerDigits(onlyDigitsText.length());
        }
    }

    private boolean isDecimalDigit(String onlyDigitsText) {
        return onlyDigitsText.contains(DOT);
    }

    private CharSequence checkRuleForDecimalDigits(String onlyDigitsPart) {
        String afterDotPart = onlyDigitsPart.substring(onlyDigitsPart.indexOf(DOT), onlyDigitsPart.length() - 1);
        if (afterDotPart.length() > mMaxDigitsAfterLength) {
            return "";
        }
        return null;
    }

    private CharSequence checkRuleForIntegerDigits(int allTextLength) {
        if (allTextLength > mMaxIntegerDigitsLength) {
            return "";
        }
        return null;
    }

    private String getOnlyDigitsPart(String text) {
        return text.replaceAll("[^0-9?!\\.]", "");
    }

    private String getAllText(CharSequence source, Spanned dest, int dstart) {
        String allText = "";
        if (!dest.toString().isEmpty()) {
            if (source.toString().isEmpty()) {
                allText = deleteCharAtIndex(dest, dstart);
            } else {
                allText = new StringBuilder(dest).insert(dstart, source).toString();
            }
        }
        return allText;
    }

    private String deleteCharAtIndex(Spanned dest, int dstart) {
        StringBuilder builder = new StringBuilder(dest);
        builder.deleteCharAt(dstart);
        return builder.toString();
    }
}
Run Code Online (Sandbox Code Playgroud)

我希望它对你有所帮助.


Rav*_*vin 5

edittext.setFilters(new InputFilter[] { new DigitsKeyListener(
                Boolean.FALSE, Boolean.TRUE) {
            int beforeDecimal = 7, afterDecimal = 2;

            @Override
            public CharSequence filter(CharSequence source, int start, int end,
                    Spanned dest, int dstart, int dend) {
                String etText = edittext.getText().toString();
                if (etText.isEmpty()){
                    return null;
                }
                String temp = edittext.getText() + source.toString();
                if (temp.equals(".")) {
                    return "0.";
                } else if (temp.toString().indexOf(".") == -1) {
                    // no decimal point placed yet
                    if (temp.length() > beforeDecimal) {
                        return "";
                    }
                } else {
                    int dotPosition ;
                    int cursorPositon = edittext.getSelectionStart();
                    if (etText.indexOf(".") == -1) {
                        Log.i("First time Dot", etText.toString().indexOf(".")+" "+etText);
                        dotPosition = temp.indexOf(".");
                        Log.i("dot Positon", cursorPositon+"");
                        Log.i("dot Positon", etText+"");
                        Log.i("dot Positon", dotPosition+"");
                    }else{
                        dotPosition = etText.indexOf(".");
                        Log.i("dot Positon", cursorPositon+"");
                        Log.i("dot Positon", etText+"");
                        Log.i("dot Positon", dotPosition+"");
                    }
                    if(cursorPositon <= dotPosition){
                        Log.i("cursor position", "in left");
                        String beforeDot = etText.substring(0, dotPosition);
                        if(beforeDot.length()<beforeDecimal){
                            return source;
                        }else{
                            if(source.toString().equalsIgnoreCase(".")){
                                return source;
                            }else{
                                return "";
                            }

                        }
                    }else{
                        Log.i("cursor position", "in right");
                        temp = temp.substring(temp.indexOf(".") + 1);
                        if (temp.length() > afterDecimal) {
                            return "";
                        }
                    }
                }

                return super.filter(source, start, end, dest, dstart, dend);
            }
        } });
Run Code Online (Sandbox Code Playgroud)


Cha*_*iga 0

虽然不是直接的解决方案,但您可以通过以下方式控制从 IME 到 EditText 的每个字符TextWatcher

关于如何使用的 SO 问答之一TextWatcher这里

更多关于TextWatcher这里

您可能需要正则表达式的帮助来匹配浮点精度模式匹配器来验证输入。