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

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

    You can do this with an an InputFilter. Apparently ther is just this Input Filter Interface you can use. Before you do it the annoying way an create a new Class that extends Input filter, u can use this shortcut with a innerclass Interface instantiation.

    Therefore you just do this:

    EditText subTargetTime = (EditText) findViewById(R.id.my_time);
    subTargetTime.setFilters( new InputFilter[] {
                    new InputFilter() {
                        @Override
                        public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                            int t = Integer.parseInt(source.toString());
                            if(t <8) { t = 8; }
                            return t+"";
    
                        }
                    }
            });
    

    In this example I check if the value of the EditText is greater than 8. If not it shall be set to 8. So apaprently you need to com up with the min max or whatever filter logic by yourself. But at least u can write the filter logic pretty neat and short directly into the EditText.

    Hope this helps

提交回复
热议问题