How to limit the text in numbers only from 0-59 in Edit Text in Android?
Here's how I like to do this:
public class InputFilterMinMax implements InputFilter {
private int min;
private int max;
public InputFilterMinMax(int min, int 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 {
int input = Integer.parseInt(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(int a, int b, int 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, 59)});
First Add input type as number and limit the number of input for editText.
editText.setInputType( InputType.TYPE_CLASS_NUMBER );
InputFilter[] FilterArray = new InputFilter[1];
FilterArray[0] = new InputFilter.LengthFilter(2);
editText.setFilters(FilterArray);
then
add a TextWatcher
to check what user typing if the value is more than 59 show a alert or any message that number will be less than 60.
editText.addTextChangedListener(new TextWatcher() {
@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
String added_number = editText.getText().toString();
if (added_number.length != 0) {
int number = Integer.parseInt(added_number);
if (number > 59)
Toast.makeText(getApplicationContext, "Not more than 59", Toast.LENGTH_SHORT).show();
}
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// TODO Auto-generated method stub
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
});
Use this code in XML to allow numbers only in Edit Text:
<EditText android:id="@+id/edit_text_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="numbers" />
To control the text values entered in that EditText:
edittext.addTextChangedListener(new TextWatcher(){
public void afterTextChanged(Editable s) {}
public void beforeTextChanged(CharSequence s, int start, int count, int after){}
public void onTextChanged(CharSequence s, int start, int before, int count){
String strEnteredVal = edittext.getText().toString();
if(!strEnteredVal.equals("")){
int num=Integer.parseInt(strEnteredVal);
if(num<60){
edittext.setText(""+num);
}else{
edittext.setText("");
}
}
});