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

后端 未结 25 1269
你的背包
你的背包 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 ...     
                 }
             }
          }
     });
    
    0 讨论(0)
  • 2020-11-22 12:23

    @Pratik Sharma

    For support negative numbers, add the following code within the filter method:

    package ir.aboy.electronicarsenal;
    
    import android.text.InputFilter;
    import android.text.Spanned;
    
    public class InputFilterMinMax implements InputFilter {
    
      private int min, max;
      int input;
    
      InputFilterMinMax(int min, int max) {
        this.min = min;
        this.max = max;
      }
    
      public InputFilterMinMax(String min, String max) {
        this.min = Integer.parseInt(min);
        this.max = Integer.parseInt(max);
      }
    
      @Override
      public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
        try {
    
          if ((dest.toString() + source.toString()).equals("-")) {
            source = "-1";
          }
    
          input = Integer.parseInt(dest.toString() + source.toString());
          if (isInRange(min, max, input))
            return null;
    
        } catch (NumberFormatException ignored) {
        }
        return "";
      }
    
      private boolean isInRange(int a, int b, int c) {
        return b > a ? c >= a && c <= b : c >= b && c <= a;
      }
    
    }
    

    Then use this from your Activity :

    findViewById(R.id.myEditText).setFilters(new InputFilter[]{ new InputFilterMinMax(1, 12)});
    

    Set your edittext with:

    android:inputType="number|numberSigned"
    
    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-11-22 12:26

    If you need range with negative numbers like -90:90, you can use this solution.

    public class InputFilterMinMax implements InputFilter {
    
    private int min, max;
    
    public InputFilterMinMax(int min, int max) {
        this.min = min;
        this.max = max;
    }
    
    public InputFilterMinMax(String min, String max) {
        this.min = Integer.parseInt(min);
        this.max = Integer.parseInt(max);
    }
    
    @Override
    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
        try {
            String stringInput = dest.toString() + source.toString();
            int value;
            if (stringInput.length() == 1 && stringInput.charAt(0) == '-') {
                value = -1;
            } else {
                value = Integer.parseInt(stringInput);
            }
            if (isInRange(min, max, value))
                return null;
        } catch (NumberFormatException nfe) {
        }
        return "";
    }
    
    private boolean isInRange(int min, int max, int value) {
        return max > min ? value >= min && value <= max : value >= max && value <= min;
    }
    }
    
    0 讨论(0)
  • 2020-11-22 12:28

    Here's my take on Pratik Sharma's answer for Kotlin and Double if any one needs it

    class InputFilterMinMax : InputFilter {
    
    private var min: Double = MIN_LIMIT
    private var max: Double = MIN_LIMIT
    
    constructor(min: Int, max: Int) {
        this.min = min.toDouble()
        this.max = max.toDouble()
    }
    
    constructor(min: String, max: String) {
        this.min = min.toDouble()
        this.max = max.toDouble()
    }
    
    constructor(min: Double, max: Double) {
        this.min = min
        this.max = max
    }
    
    override fun filter(
        source: CharSequence,
        start: Int,
        end: Int,
        dest: Spanned,
        dstart: Int,
        dend: Int
    ): CharSequence? {
        try {
            val input = (dest.toString() + source.toString()).toDouble()
            if (isInRange(min, max, input))
                return null
        } catch (nfe: NumberFormatException) {
            Timber.e(nfe)
        }
    
        return ""
    }
    
    private fun isInRange(a: Double, b: Double, c: Double): Boolean {
        return if (b > a) c in a..b else c in b..a
    }
    }
    
    0 讨论(0)
  • 2020-11-22 12:30

    I made a simpler way to set a min/max to an Edittext. I use arithmetic keypad and I work with this method:

     private int limit(EditText x,int z,int limin,int limax){
    
        if( x.getText().toString()==null || x.getText().toString().length()==0){
            x.setText(Integer.toString(limin));
            return z=0;
        }
        else{
            z = Integer.parseInt(x.getText().toString());
             if(z <limin || z>limax){
                 if(z<10){
                     x.setText(Integer.toString(limin));
                    return  z=0;
                 }
                else{
                    x.setText(Integer.toString(limax));
                    return z=limax;
                }
    
             }
             else
                return z = Integer.parseInt(x.getText().toString());
        }
     }
    

    The method accepts all of your values but if a value of users in not adhere to your limits it will be set automatically to the min/max limit. For ex. limit limin=10, limax =80 if the user sets 8, automatically 10 is saved to a variable and EditText is set to 10.

    0 讨论(0)
提交回复
热议问题