I want to force users to enter a Number and i'm using that (and it's working fine):
android:inputType="number"
I want to force the user to make the input just two numbers (Int or Double does not matter) and those numbers must be between 0 and 20 (or 0.0 and 20.0) : e.g : 0 or 0.0 1 or 1.5 (1.0 etc) . . . 20 or 20.0
Here's how I like to do this:
add this for edit text
android:inputType="numberDecimal"
(or)
android:digits="0123456789."
Kotlin::
class InputFilterMinMax(min:Float, max:Float): InputFilter {
private var min:Float = 0.0F
private var max:Float = 0.0F
init{
this.min = min
this.max = max
}
override 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 in a..b else c in b..a
}
}
Then set the filter on your EditText:
myEditText.setFilters(arrayOf<InputFilter>(InputFilterMinMax(0.0F, 20.0F)))
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;
}
}
Then set the filter on your EditText:
myEditText.setFilters(new InputFilter[]{new InputFilterMinMax(0.0, 20.0)});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With