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

后端 未结 25 1633
你的背包
你的背包 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条回答
  •  萌比男神i
    2020-11-22 12:46

    Extension of Pratik's and Zac's answer. Zac fixed a small bug of Pratik's in his answer. But I notcied that code doesn't support negative values, it will throw a NumberFormatException. To fix that, and allow the MIN to be negative, use the following code.

    Add this line (In bold) between the other two lines:

    newVal = newVal.substring(0, dstart) + source.toString()+ newVal.substring(dstart, newVal.length());

    if(newVal.equalsIgnoreCase("-") && min < 0)return null;

    int input = Integer.parseInt(newVal);

    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
        try {
            // Remove the string out of destination that is to be replaced
            String newVal = dest.toString().substring(0, dstart) + dest.toString().substring(dend, dest.toString().length());
            // Add the new string in
            newVal = newVal.substring(0, dstart) + source.toString() + newVal.substring(dstart, newVal.length());
            //****Add this line (below) to allow Negative values***// 
            if(newVal.equalsIgnoreCase("-") && min < 0)return null;
            int input = Integer.parseInt(newVal);
            if (isInRange(min, max, input))
                return null;
        } catch (NumberFormatException nfe) {
            nfe.printStackTrace();
        }
        return "";
    }
    

提交回复
热议问题