17

我有一个EditText必须允许用户输入最多 7 个数字和两个小数位的框。输入七位数字后,不应再添加一位数字,但我可以允许最多两位小数。我对小数点后 2 位使用十进制过滤器,并在 XML 中使用此代码

android:maxLength="7"    
android:imeOptions="actionDone"                  
android:inputType="numberDecimal"

EditText允许到enter8 位。如何解决?

4

9 回答 9

29

在 onCreate 下试试这个

 youreditText.setFilters(new InputFilter[] {new DecimalDigitsInputFilter(5,1)});

这在你的程序中的任何地方

   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;
            }

        }
于 2014-04-29T10:09:23.153 回答
18

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

mEditText.setFilters(new InputFilter[]{new DigitsInputFilter(maxDigitsBeforeDot, maxDigitsAfterDot, maxValue)});

如果您不想在 dot just put之前或之后限制数字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();
    }
}

我希望它对你有帮助。

于 2017-08-15T14:48:20.747 回答
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);
            }
        } });
于 2014-02-15T18:55:42.470 回答
2
public class DecimalDigitsInputFilter implements InputFilter {

    Pattern mPattern;
    int digitsBeforeZero;

    public DecimalDigitsInputFilter(int digitsBeforeZero, int digitsAfterZero) {
        this.digitsBeforeZero = digitsBeforeZero;
        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()) {
            if (dest.toString().contains(".")) {
                if (dest.toString().substring(dest.toString().indexOf(".")).length() > 2) {
                    return "";
                }
                return null;
            } else if (!Pattern.compile("[0-9]{0," + (digitsBeforeZero - 1) + "}").matcher(dest).matches()) {
                if (!dest.toString().contains(".")) {
                    if (source.toString().equalsIgnoreCase(".")) {
                        return null;
                    }
                }
                return "";
            } else {
                return null;
            }
        }

        return null;
    }
}
于 2017-02-24T07:17:00.580 回答
1

您可以使用此输入过滤器来解决您的问题。设置过滤器:对于 4 位数字和两个小数点

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) {

        String s = Html.toHtml(dest).replaceAll("\\<.*?>","").replaceAll("\n","");
        Matcher matcher = mPattern.matcher(dest);
        if (!matcher.matches())
            return "";
        try {
            if(Double.parseDouble(s)<9999.99 && s.contains(".")) {
                return null;
            }else if ((Double.parseDouble(s)<1000 && !s.contains("."))||source.equals(".")) {
                return null;
            }else {
                return "";
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}

    editText.setFilters(new InputFilter[]{new DecimalDigitsInputFilter(7, 2)});
于 2018-02-28T05:13:55.967 回答
1

首先在 onCreate 中创建这个

DecimalFormat amountFormate  = new DecimalFormat("#######.##");
amountFormate.setMinimumFractionDigits(2);
amountFormate.setMaximumFractionDigits(2);
editText.setText(amountFormate.format(yourValue));
  1. 2是你的小数
  2. yourValue 只不过是双变量

例子:

double amount = 1234567.54;
editText.setText(amountFormate.format(amount));

输出- > 1234567.54

于 2020-05-13T10:15:40.347 回答
0

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

关于如何使用的 SO Q&A 之一TextWatcher这里

更多关于TextWatcher这里

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

于 2013-07-02T10:58:44.420 回答
0

您可以在使用 Android 数据绑定时增强它,如下所示:

定义自定义绑定适配器:

@BindingAdapter({"digitsBeforeZero", "digitsAfterZero"})
public void bindAmountInputFilter(EditText view, int digitsBeforeZero, int digitsAfterZero) {
       view.setFilters(new InputFilter[]{new DecimalDigitsInputFilter(digitsBeforeZero, digitsAfterZero)});
 }

向 EditText 添加属性:

app:digitsBeforeZero="@{7}"
app:digitsAfterZero="@{2}"

它会自动为edittext设置输入过滤器

于 2017-11-22T13:20:44.763 回答
0
editText.addTextChangedListener(new TextWatcher() {
        String firstString;
        String beforeInt = "";
        String beforeDec = "";
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            txtAmt.setText("");
            firstString = charSequence.toString();
            String[] rupee = firstString.split("\\.");
            if ( rupee.length > 0 )
                beforeInt = rupee[0];
            if ( rupee.length > 1 )
                beforeDec = rupee[1];

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            try {

                String amount = charSequence.toString().replaceAll(",","");
                if ( txtAmt != null  && !amount.isEmpty()){
                    String[] rupee = amount.split("\\.");
                    if ( rupee.length == 0 )
                        return;
                    String intPart = rupee[0];
                    int arrayLength = rupee.length;
                    if ( arrayLength == 2 ){
                        String decPart = rupee[1];
                        if ( decPart.length() == 1 )
                            decPart += "0";
                        if ( intPart.length() > 6 || decPart.length() > 2 ){
                                editText.removeTextChangedListener(this);
                                firstString = beforeInt;
                                if ( !beforeDec.isEmpty() )
                                    firstString += "."+beforeDec;
                                editText.setText( firstString );

                                editText.setSelection( firstString.length());
                                editText.addTextChangedListener( this );



                        }

                    }


                }
            }catch (Exception e){
               //Do nothing
            }
        }

        @Override
        public void afterTextChanged(Editable s) {
            //Do nothing
        }
    });
于 2018-05-24T07:02:23.450 回答