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

后端 未结 25 1620
你的背包
你的背包 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:47

    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 "";
    }
    

提交回复
热议问题