【问题标题】:Android: EditText with max decimal and max numberAndroid:具有最大小数和最大数字的 EditText
【发布时间】:2017-08-30 08:02:44
【问题描述】:

我正在尝试为我的编辑文本创建一个过滤器,以便在点后有一个最大小数点。我想用这个editText来输入钱。

我将inputType 设置为numberDecimal,但我可以写出小数点后有很多位数的无限数。

我在 StackOverFlow 上发现了很多线程来过滤最大小数,但我也想添加一个最大数字。

所以,我只想让过滤器在 [01000] 之间写入 2 位 小数点后,但是 1000 是最大值。 (不能写 1000.99)。

谢谢

【问题讨论】:

标签: java android android-edittext


【解决方案1】:

您可以使用 InputFilters 实现这一目标

首先你需要为十进制数字创建一个输入过滤器

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

}

然后创建另一个输入过滤器来限制 0 到 1000 之间的数字

public class InputFilterMinMax implements InputFilter {

private int min, max;

public InputFilterMinMax(int min, int max) {
    this.min = min;
    this.max = max;
}

public InputFilterMinMax(String min, String max) {
    this.min = Integer.parseInt(min);
    this.max = Integer.parseInt(max);
}

@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {   
    try {
        int input = Integer.parseInt(dest.toString() + source.toString());
        if (isInRange(min, max, input))
            return null;
    } catch (NumberFormatException nfe) { }     
    return "";
}

private boolean isInRange(int a, int b, int c) {
    return b > a ? c >= a && c <= b : c >= b && c <= a;
}
}

然后将这些输入过滤器设置为您的编辑文本

 edittext.setFilters(new InputFilter[]{ new InputFilterMinMax("0", "1000"), new DecimalDigitsInputFilter(3,2)});

我没有尝试过代码,但我认为这会让你走上正确的道路。

参考资料:

Limit Decimal Places in Android EditText

Is there a way to define a min and max value for EditText in Android?

【讨论】:

  • 好的,谢谢,我们可以添加很多过滤器。你的代码不工作,但我要检查在哪里。
猜你喜欢
  • 2012-11-07
  • 2014-01-23
  • 1970-01-01
  • 2020-04-03
  • 1970-01-01
  • 2016-04-23
  • 1970-01-01
  • 2013-07-30
  • 2013-01-18
相关资源
最近更新 更多