Is there a way to define a min and max value for EditText in Android?

后端 未结 25 1243
你的背包
你的背包 2020-11-22 11:51

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.

25条回答
  •  有刺的猬
    2020-11-22 12:26

    If you need range with negative numbers like -90:90, you can use this solution.

    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 {
            String stringInput = dest.toString() + source.toString();
            int value;
            if (stringInput.length() == 1 && stringInput.charAt(0) == '-') {
                value = -1;
            } else {
                value = Integer.parseInt(stringInput);
            }
            if (isInRange(min, max, value))
                return null;
        } catch (NumberFormatException nfe) {
        }
        return "";
    }
    
    private boolean isInRange(int min, int max, int value) {
        return max > min ? value >= min && value <= max : value >= max && value <= min;
    }
    }
    

提交回复
热议问题