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

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

    @Patrik’s code has a nice idea but with a lot of bugs. @Zac and @Anthony B ( negative numbers solutions) have solve some of them, but @Zac’s code still have 3 mayor bugs:

    1. If user deletes all entries in the EditText, it’s impossible to type any number again.. Of course this can be controlled using a EditText changed listener on each field, but it will erase out the beauty of using a common InputFilter class for each EditText in your app.

    2. Has @Guernee4 says, if for example min = 3, it’s impossible to type any number starting with 1.

    3. If for example min = 0, you can type has many zeros you wish, that it’s not elegant the result. Or also, if no matter what is the min value, user can place the cursor in the left size of the first number, an place a bunch of leading zeros to the left, also not elegant.

    I came up whit these little changes of @Zac’s code to solve this 3 bugs. Regarding bug # 3, I still haven't been able to completely remove all leading zeros at the left; It always can be one, but a 00, 01, 0100 etc in that case, is more elegant an valid that an 000000, 001, 000100, etc.etc. Etc.

    Here is the code:

    @Override
        public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
            try {
    
                // Using @Zac's initial solution
                String lastVal = dest.toString().substring(0, dstart) + dest.toString().substring(dend);
                String newVal = lastVal.substring(0, dstart) + source.toString() + lastVal.substring(dstart);
                int input = Integer.parseInt(newVal);
    
                // To avoid deleting all numbers and avoid @Guerneen4's case
                if (input < min && lastVal.equals("")) return String.valueOf(min);
    
                // Normal min, max check
                if (isInRange(min, max, input)) {
    
                    // To avoid more than two leading zeros to the left
                    String lastDest = dest.toString();
                    String checkStr = lastDest.replaceFirst("^0+(?!$)", "");
                    if (checkStr.length() < lastDest.length()) return "";
    
                    return null;
                }
            } catch (NumberFormatException ignored) {}
            return "";
        }
    

    Have a nice day!

提交回复
热议问题