我想强迫用户输入一个数字,而我正在使用它(并且可以正常工作):
android:inputType="number"
我想强迫用户只输入两个数字(Int或Double无关紧要),并且这些数字必须在0到20(或0.0到20.0)之间: 例如: 0或0.0 1或1.5(1.0等) 。 。 。 20或20.0
答案 0 :(得分:3)
这就是我喜欢的方式:
添加此内容以编辑文本
android:inputType="numberDecimal"
(或)
android:digits="0123456789."
科特琳::
class InputFilterMinMax(min:Float, max:Float):InputFilter {
private val min:Float = 0.toFloat()
private val max:Float = 0.toFloat()
init{
this.min = min
this.max = max
}
fun filter(source:CharSequence, start:Int, end:Int, dest:Spanned, dstart:Int, dend:Int):CharSequence {
try
{
val input = (dest.subSequence(0, dstart).toString() + source + dest.subSequence(dend, dest.length())).toFloat()
if (isInRange(min, max, input))
return null
}
catch (nfe:NumberFormatException) {}
return ""
}
private fun isInRange(a:Float, b:Float, c:Float):Boolean {
return if (b > a) c >= a && c <= b else c >= b && c <= a
}
}
然后在您的EditText上设置过滤器:
myEditText.setFilters(arrayOf<InputFilter>(InputFilterMinMax(0.0, 20.0)))
Java:
public class InputFilterMinMax implements InputFilter {
private float min;
private float max;
public InputFilterMinMax(float min, float max) {
this.min = min;
this.max = max;
}
@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
//noinspection EmptyCatchBlock
try {
float input = Float.parseFloat(dest.subSequence(0, dstart).toString() + source + dest.subSequence(dend, dest.length()));
if (isInRange(min, max, input))
return null;
} catch (NumberFormatException nfe) { }
return "";
}
private boolean isInRange(float a, float b, float c) {
return b > a ? c >= a && c <= b : c >= b && c <= a;
}
}
然后在您的EditText上设置过滤器:
myEditText.setFilters(new InputFilter[]{new InputFilterMinMax(0.0, 20.0)});
答案 1 :(得分:0)
使用TextWatcher