How to restrict to input time for edittext in android

后端 未结 5 1105
甜味超标
甜味超标 2021-01-17 18:34

I have to allow user to input only time in ##:## format in edit text on the fly, is there any way to achieve it? I have used below code but it doest not working.

I a

5条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-17 19:08

    Try this, I simply edited the code you provided....

    InputFilter[] timeFilter = new InputFilter[1];
    
    timeFilter[0] = new InputFilter() {
        public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
    
            if (source.length() == 0) {
                return null;// deleting, keep original editing
            }
    
            String result = "";
            result += dest.toString().substring(0, dstart);
            result += source.toString().substring(start, end);
            result += dest.toString().substring(dend, dest.length());
    
            if (result.length() > 5) {
                return "";// do not allow this edit
            }
    
            boolean allowEdit = true;
            char c;
            if (result.length() > 0) {
                c = result.charAt(0);
                allowEdit &= (c >= '0' && c <= '2' && !(Character.isLetter(c)));
            }
    
            if (result.length() > 1) {
                c = result.charAt(1);
                allowEdit &= (c >= '0' && c <= '9' && !(Character.isLetter(c)));
            }
    
            if (result.length() > 2) {
                c = result.charAt(2);
                allowEdit &= (c == ':'&&!(Character.isLetter(c)));
            }
    
            if (result.length() > 3) {
                c = result.charAt(3);
                allowEdit &= (c >= '0' && c <= '5' && !(Character.isLetter(c)));
            }
    
            if (result.length() > 4) {
                c = result.charAt(4);
                allowEdit &= (c >= '0' && c <= '9'&& !(Character.isLetter(c)));
            }
    
            return allowEdit ? null : "";
        }
    };
    

    This works absolutely fine for me. Accepts time in format hh:mm only (no other character accepted)

提交回复
热议问题