Is there a way to define a min and max value for EditText in Android?
I want to define a min and max value for an EditText
.
For example: if any person tries to enter a month value in it, the value must be between 1-12.
I can do it by using TextWatcher
but I want to know if there is any other way to do it in layout file or elsewhere.
Edit:
I don't want to limit character count. I want to limit the value. For example, if I limit month EditText
w characters when I enter 12 it will accept it but if I enter 22 it mustn't accept it while I am entering.
Solution 1:
First make this class :
package com.test;
import android.text.InputFilter;
import android.text.Spanned;
public class InputFilterMinMax implements InputFilter {
private int min, max;
public InputFilterMinMax(int min, int max) {
this.min = min;
this.max = max;
}
public InputFilterMinMax(String min, String max) {
this.min = Integer.parseInt(min);
this.max = Integer.parseInt(max);
}
@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
try {
int input = Integer.parseInt(dest.toString() + source.toString());
if (isInRange(min, max, input))
return null;
} catch (NumberFormatException nfe) { }
return "";
}
private boolean isInRange(int a, int b, int c) {
return b > a ? c >= a && c <= b : c >= b && c <= a;
}
}
Then use this from your Activity :
EditText et = (EditText) findViewById(R.id.myEditText);
et.setFilters(new InputFilter[]{ new InputFilterMinMax("1", "12")});
This will allow user to enter values from 1 to 12 only.
EDIT :
Set your edittext with android:inputType="number"
.
You can find more details at https://www.techcompose.com/how-to-set-minimum-and-maximum-value-in-edittext-in-android-app-development/.
Thanks.
Solution 2:
There is a small error in Pratik's code. For instance, if a value is 10 and you add a 1 at the beginning to make 110, the filter function would treat the new value as 101.
See below for a fix to this:
@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
try {
// Removes string that is to be replaced from destination
// and adds the new string in.
String newVal = dest.subSequence(0, dstart)
// Note that below "toString()" is the only required:
+ source.subSequence(start, end).toString()
+ dest.subSequence(dend, dest.length());
int input = Integer.parseInt(newVal);
if (isInRange(min, max, input))
return null;
} catch (NumberFormatException nfe) { }
return "";
}