【问题标题】:decimal input filter android十进制输入过滤器android
【发布时间】:2016-05-05 10:56:18
【问题描述】:

我想让 EditText 采用十进制值,其中允许小数点后 2 位(可选)。值可以是:

xxxx

xxxx.x

xx.xx

.xx

.x

x.x

我已经尝试了很多在 S/O 中找到的解决方案,并且我找到了合适的正则表达式来满足我的解决方案。但是没有一个能满足我的要求。一些解决方案满足要求,但不允许在小数点前进行编辑。假设,当edittext值为.xx时,小数点(.)之前不能编辑。

谁能指出正确的解决方案。

注意:在 EditText 中使用 maxLength 属性。

【问题讨论】:

  • 正则表达式应该做什么?匹配所有小数?
  • 你需要什么作为o/p?
  • 你能找到解决办法吗?我有同样的问题。我无法在小数点前添加新字符...
  • @atasoyh,找不到任何正则表达式解决方案,与 TextWatcher 一起克服了这种情况。

标签: android regex


【解决方案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;
        }


    }

并将过滤器设置为编辑文本

editText.setFilters(new InputFilter[] { new DecimalDigitsInputFilter(10, 2) });

【讨论】:

  • 我也用过这个。这符合我的要求,但不允许在小数点之前修改(。)
  • 你到底想要什么?
  • 使用您的解决方案,在 Edittext 中输入 .33 值,请尝试在小数点 (.) 前添加一些内容。我敢肯定这不会发生。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-11-14
  • 1970-01-01
  • 2013-03-16
  • 2019-03-23
  • 2023-03-18
  • 1970-01-01
  • 2021-05-31
相关资源
最近更新 更多