Skip to content
Advertisement

Is there a way to define a min and max value for a EditText. EG 20 – 200 (not starting at 1)

I keep seeing this example everywhere I look to find a way to define the min and max of a EditText. I kind of understand what it does but I found that it breaks if the min is bigger then 10. Is there any way this code could be changed so that the min can be any number? And is there any easier way of doing this as it seems to be over-complicated for a simple task?

 ClassName.setFilters(new InputFilter[]{ new InputFilterMinMax("1", "200")});
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;
    }

Advertisement

Answer

there will be some event, Here I’m taking button click event

@Override
public void onClick(View view) {

String guessSize=editText.getText().toString();
if(Integer.parseInt(guessSize)<=20 || Integer.parseInt(guessSize)>=200)
{
    //Anything you want
    Toast.makeText(MainActivity.this, "No wroking", Toast.LENGTH_SHORT).show();
}
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement