android - 用小数限制android中的编辑文本

标签 android

我对 editText 中的数量限制有疑问。我希望用户只能输入 1-70 之间的数字。当用户想要输入 70.01 或更多时,我不想允许它们。只允许两位小数。总长度为 5 个字符,包括点。

我可以限制小数点前后。并且还限制了 70,但用户可以在我想阻止的编辑文本中输入 70.99(不知道为什么)。当用户输入 71 或更多时我的验证工作

这是我在 fragment 中使用的构造函数

     txtno.setFilters(new InputFilter[] {new DecimalDigitsInputFilter(Integer.parseInt(getString(R.string.length)),2,txtno)});

这是小数点前后的

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

    mTextView.setKeyListener(DigitsKeyListener.getInstance(true,true));
    String etText = mTextView.getText().toString();
    String temp = mTextView.getText() + source.toString();
    if (temp.equals(".")) {

        return "0.";
    } else if (temp.toString().indexOf(".") == -1) {

        // no decimal point placed yet
        if (temp.length() > mMyint) {

            return "";
        }
    } else {

        int dotPosition;
        int cursorPositon = mTextView.getSelectionStart();

        if (etText.indexOf(".") == -1) {

            dotPosition = temp.indexOf(".");
        } else {

            dotPosition = etText.indexOf(".");
        }
        if (cursorPositon <= dotPosition) {

            String beforeDot = etText.substring(0, dotPosition);
            if (beforeDot.length() < mMyint) {

                    return source;
            } else {

                if (source.toString().equalsIgnoreCase(".")) {

                    return source;
                    } else {

                    return "";
                    }
            }
        } else {

            temp = temp.substring(temp.indexOf(".") + 1);
            if (temp.length() > mMydec) {

                return "";
            }
        }
    }
    return null;
}

& 这是限制 70 的 textWatcher

public void afterTextChanged(Editable s) {

    try{

        if(Integer.parseInt(s.toString())>70){

            s.replace(0, s.length(), s.toString());
        }
    }catch(Exception e){}

提前致谢。

最佳答案

问题是您尝试解析 int - 您需要解析 double。

关于android - 用小数限制android中的编辑文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27124065/

相关文章:

Android Google Map IconGenerator - 制作透明标记图标

android - 简单的 JSON 应用程序在 ICS 上崩溃,在 Gingerbread 中工作正常

php - 如何将图片上传到 Php 服务器并存储在 phpmyadmin 中

fortumo 应用内支付导致 Android 应用崩溃

android - android中ListView的过滤和排序问题

java - 关于 Android 中 putExtra 方法顺序的奇怪行为

android - 错误 : Expected resource of type styleable [ResourceType] error

java - 如何从给定类 Item 获取数组?

机器人 : inflated view with a different orientation than the activity

java - Android 在另一个异步任务中调用异步任务?