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

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

    //still has some problem but Here you can use min, max at any range (positive or negative)

    // in filter calss
     @Override
     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
                int input;
                String newVal = dest.toString() + source.toString();
                if (newVal.length() == 1 && newVal.charAt(0) == '-') {
                    input = min; //allow
                }
                else {
                    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());
                    input = Integer.parseInt(newVal);
                }
    
                //int input = Integer.parseInt(dest.toString() + source.toString());
    
                if (isInRange(min, max, input))
                    return null;
            } catch (NumberFormatException nfe) {
            }
            return "";
        }
    
    //also the filler must set as below: in the edit createview
    // to allow enter number and backspace.
    et.setFilters(new InputFilter[]{new InputFilterMinMax(min >= 10 ?  "0" : String.valueOf(min), max >-10 ? String.valueOf(max) :"0" )});
    
    
    
    //and at same time must check range in the TextWatcher()
    et.addTextChangedListener(new
     TextWatcher() {
    
          @Override
          public void afterTextChanged (Editable editable)
          {
             String tmpstr = et.getText().toString();
             if (!tmpstr.isEmpty() && !tmpstr.equals("-") ) {
                 int datavalue = Integer.parseInt(tmpstr);
                 if ( datavalue >= min || datavalue <= max) {
                   // accept data ...     
                 }
             }
          }
     });
    

提交回复
热议问题