Android edittext两位小数

时间:2018-02-12 18:42:39

标签: android android-edittext

我有一个editText,用户可以在其中输入金额。所以我希望这个editText不允许用户输入两个以上的小数位。

示例: 23.45(不是23.4567)

实现类似内容的最佳方式是什么?

6 个答案:

答案 0 :(得分:4)

你应该使用InputFilter这是一个例子

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(5,2)});

答案 1 :(得分:1)

你可以使用以下代码:

或。请看一下:http://v4all123.blogspot.in/2013/05/set-limit-for-fraction-in-decimal.html

    et = (EditText) vw.findViewById(R.id.tx_edittext);

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

                @Override
                public CharSequence filter(CharSequence source, int start, int end,
                        Spanned dest, int dstart, int dend) {
                    String temp = et.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 {
                        temp = temp.substring(temp.indexOf(".") + 1);
                        if (temp.length() > afterDecimal) {
                            return "";
                        }
                    }

                    return super.filter(source, start, end, dest, dstart, dend);
                }
            }
    });

,或者

et.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
    String text = arg0.toString();
    if (text.contains(".") && text.substring(text.indexOf(".") + 1).length() > 2) {
        et.setText(text.substring(0, text.length() - 1));
        et.setSelection(et.getText().length());
    }
}

public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {

}

public void afterTextChanged(Editable arg0) {
}
});

答案 2 :(得分:0)

           input.addTextChangedListener(new TextWatcher() {

                public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
                    String text = arg0.toString();
                    if (arg0.length() <= 1) {
                        if (text.contains(".") && text.indexOf(".") == 0) {
                            holder.input.setText("0.");
                            holder.input.setSelection(holder.input.getText().length());
                        }

                    } else {
                        if (text.contains(".") &&
                                text.indexOf(".") != text.length() - 1 &&
                                String.valueOf(text.charAt(text.length() - 1)).equals(".")) {
                            holder.input.setText(text.substring(0, text.length() - 1));
                            holder.input.setSelection(holder.input.getText().length());
                        }
                        if (text.contains(".") && text.substring(text.indexOf(".") + 1).length() > 2) {
                            holder.input.setText(text.substring(0, text.length() - 1));
                            holder.input.setSelection(holder.input.getText().length());
                        }
                    }

                }

                public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {

                }

                public void afterTextChanged(Editable arg0) {
                }
            });

答案 3 :(得分:0)

Kotlin解决方案,其扩展名为EditText:

创建以下EditText十进制限制器函数,其中包含一个 TextWatcher ,该函数将查找文本更改,例如检查小数位数和用户是否仅输入'。 / strong>符号,然后以0开头。

fun EditText.addDecimalLimiter(maxLimit: Int = 2) {

    this.addTextChangedListener(object : TextWatcher {

        override fun afterTextChanged(s: Editable?) {
            val str = this@addDecimalLimiter.text!!.toString()
            if (str.isEmpty()) return
            val str2 = decimalLimiter(str, maxLimit)

            if (str2 != str) {
                this@addDecimalLimiter.setText(str2)
                val pos = this@addDecimalLimiter.text!!.length
                this@addDecimalLimiter.setSelection(pos)
            }
        }

        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

        }

        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {

        }

    })
}

fun EditText.decimalLimiter(string: String, MAX_DECIMAL: Int): String {

    var str = string
    if (str[0] == '.') str = "0$str"
    val max = str.length

    var rFinal = ""
    var after = false
    var i = 0
    var up = 0
    var decimal = 0
    var t: Char

    val decimalCount = str.count{ ".".contains(it) }

    if (decimalCount > 1)
        return str.dropLast(1)

    while (i < max) {
        t = str[i]
        if (t != '.' && !after) {
            up++
        } else if (t == '.') {
            after = true
        } else {
            decimal++
            if (decimal > MAX_DECIMAL)
                return rFinal
        }
        rFinal += t
        i++
    }
    return rFinal
}

您可以按以下方式使用它:

val decimalText: EditText = findViewById(R.id.your_edit_text_id)
decimalText.addDecimalLimiter() // This will by default set the editText with 2 digit decimal
decimalText.addDecimalLimiter(3) // 3 or any number of decimals based on your requirements


其他步骤:

还要在布局文件中将 inputType 设置为numberDecimal,该文件仅显示数字键盘

<EditText
android:inputType="numberDecimal" />

OR

您可以通过编程方式设置inputType,如下所示:

decimalText.inputType = InputType.TYPE_CLASS_NUMBER

我从this帖子中得到了帮助。

答案 4 :(得分:0)

科特琳:

请在项目中任何不在类中的kotlin文件中的扩展功能下面保留扩展名。 (可以在类块之外,也可以在单独的文件中全局访问)

fun String.removeAfter2Decimal(et: EditText) {
return if (this.isNullOrEmpty() || this.isNullOrBlank() || this.toLowerCase() == "null") {
    //
} else {
    if(this.contains(".")) {
        var lastPartOfText = this.split(".")[this.split(".").size-1]

        if (lastPartOfText.count() > 2) {
            try {
                lastPartOfText = this.substring(0, this.indexOf(".")+3)
                et.setText(lastPartOfText)
                et.setSelection(lastPartOfText.length)
            } catch (e: Exception) {
                e.printStackTrace()
            }

        } else {

        }
    } else {

    }
  }
}

现在使用,如下所示:

myEditText.addTextChangedListener(object : TextWatcher {

        override fun afterTextChanged(editable: Editable?) {

        }

        override fun beforeTextChanged(cs: CharSequence?, p1: Int, p2: Int, p3: Int) {

        }

        override fun onTextChanged(cs: CharSequence?, p1: Int, p2: Int, p3: Int) {
            
            val mText = binding.etAmount.text.toString()

            mText.removeAfter2Decimal(binding.etAmount) // This will help to remove after 2 decimal text

        }
    })

P.S:我需要TextWatcher来完成其他工作,因此我没有将TextWatcher放在自定义函数中。在我的项目中效果很好。

谢谢:)

答案 5 :(得分:0)

使用 InputFilter 的 Kotlin 解决方案

class DecimalDigitsInputFilter(digitsBeforeZero: Int, digitsAfterZero: Int) : InputFilter {

    //                                             digitsBeforeZero  or       digitsBeforeZero + dot + digitsAfterZero
    private val pattern = Pattern.compile("(\\d{0,$digitsBeforeZero})|(\\d{0,$digitsBeforeZero}\\.\\d{0,$digitsAfterZero})")

    override fun filter(source: CharSequence, start: Int, end: Int, dest: Spanned, dstart: Int, dend: Int): CharSequence? {
        return if (source.isEmpty()) {
            // When the source text is empty, we need to remove characters and check the result
            if (pattern.matcher(dest.removeRange(dstart, dend)).matches()) {
                // No changes to source
                null
            } else {
                // Don't delete characters, return the old subsequence
                dest.subSequence(dstart, dend)
            }
        } else {
            // Check the result
            if (pattern.matcher(dest.replaceRange(dstart, dend, source)).matches()) {
                // No changes to source
                null
            } else {
                // Return nothing
                ""
            }
        }
    }
}

你可以这样使用它:

editText.filters = arrayOf(DecimalDigitsInputFilter(5, 2))