英文:
Edittext to accept Price format in android
问题
我有一个用于输入价格的EditText
字段。
我可以在其中添加多个小数点,但我想让它只接受单个小数输入,我该如何实现?我尝试过digit="0123456789."
。
英文:
I have an EditText
field which used to input price.
I can add multiple decimals in it but I want to make it to accept a single decimal input, how can i achieve it? I tried digit="0123456789."
答案1
得分: 2
以下是翻译好的部分:
/**
* 定义了CurrencyInputFilter对象。
* 它只允许输入0到9999.99之间的值。
*/
class CurrencyInputFilter(val maxDigitsBeforeDecimalPoint: Int = 4, val maxDigitsAfterDecimalPoint: Int = 2) : InputFilter {
override fun filter(source: CharSequence, start: Int, end: Int,
dest: Spanned, dstart: Int, dend: Int): CharSequence? {
val builder = StringBuilder(dest)
builder.replace(dstart, dend, source
.subSequence(start, end).toString())
return if (!builder.toString().matches("(([1-9]{1})([0-9]{0," + (maxDigitsBeforeDecimalPoint - 1) + "})?)?(\\.[0-9]{0," + maxDigitsAfterDecimalPoint + "})?".toRegex())) {
if (source.isEmpty()) dest.subSequence(dstart, dend) else ""
} else null
}
}
你可以像这样使用它:
// 添加输入过滤器以限制价格在0到9999.99之间
priceEdit.filters = arrayOf<InputFilter>(CurrencyInputFilter())
注意:你可以在构造函数参数中更改数字的位数。
英文:
To do this, I'm using the following `InputFilter``
/**
* Definition of the CurrencyInputFilter object.
* It allows only value from 0 to 9999.99
*/
class CurrencyInputFilter(val maxDigitsBeforeDecimalPoint: Int = 4, val maxDigitsAfterDecimalPoint: Int = 2) : InputFilter {
override fun filter(source: CharSequence, start: Int, end: Int,
dest: Spanned, dstart: Int, dend: Int): CharSequence? {
val builder = StringBuilder(dest)
builder.replace(dstart, dend, source
.subSequence(start, end).toString())
return if (!builder.toString().matches(("(([1-9]{1})([0-9]{0," + (maxDigitsBeforeDecimalPoint - 1) + "})?)?(\\.[0-9]{0," + maxDigitsAfterDecimalPoint + "})?").toRegex())) {
if (source.isEmpty()) dest.subSequence(dstart, dend) else ""
} else null
}
}
You can use it like this:
// add input filter to limit price from 0 to 9999.99
priceEdit.filters = arrayOf<InputFilter>(CurrencyInputFilter())
Note: you can change the number of digits in the constructor parameters.
答案2
得分: 0
只需将此行添加到您的XML中的EditText
视图中:android:inputType="numberDecimal"
。
此外,通过以下代码检查输入是否有效:
try {
val number = editText.text.toString().toDouble()
} catch (e: Exception) {
Log.v("INVALID", "Invalid price")
}
英文:
Just add this line android:inputType="numberDecimal"
to your EditText
view in your xml and it will work.
Also, check if the input entered is valid or not by following code
try {
val number = editText.text.toString().toDouble()
} catch (e: Exception) {
Log.v("INVALID", "Invalid price")
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论