Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EditText Values in range

Tags:

android

I would like to enter the values in a range like 1-60. The EditText shouldn't accept values like 61,62..., or 0,-1,-2...

How can we give the range 1-60 to EditText in android? I have done in main.xml as

 <EditText android:layout_height="wrap_content" 
    android:id="@+id/editText1" 
    android:layout_width="160dip" 
    android:inputType="number">
    </EditText>
like image 423
prasad.gai Avatar asked Mar 22 '11 12:03

prasad.gai


2 Answers

I fixed Daniel Wilson's 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 {
        //The commented line below only works if you append/modify the end of the text (not the beginning or middle)
        //int input = Integer.parseInt(dest.toString() + source.toString());
        //corrected solution below (3lines)
        CharSequence part1 = dest.subSequence(0, dstart);
        CharSequence part2 = dest.subSequence(dend, dest.length());
        int input = Integer.parseInt(part1 + source.toString() + part2);

        if (isInRange(min, max, input))
            return null;
    } catch (NumberFormatException nfe) { }
    return "";
}

private boolean isInRange(int a, int b, int c) {
    return b > a ? c >= a && c <= b : c >= b && c <= a;
}
}

Finally add the InputFilter to your EditText control:

mCentsEditText = (EditText)findViewById(R.id.cents_edit_text);
InputFilterMinMax filter = new InputFilterMinMax("1", "60") {};
mCentsEditText.setFilters(new InputFilter[]{filter});
like image 156
ZP007 Avatar answered Oct 14 '22 13:10

ZP007


You can assign a TextWatcher to your EditText and listen for text changes there, for example:

public void afterTextChanged(Editable s) {
   try {
     int val = Integer.parseInt(s.toString());
     if(val > 60) {
        s.replace(0, s.length(), "60", 0, 2);
     } else if(val < 1) {
        s.replace(0, s.length(), "1", 0, 1);
     }
   } catch (NumberFormatException ex) {
      // Do something
   }
}

As mentioned by Devunwired, notice that calls to s.replace() will call the TextWatcher again recursively.

It is typical to wrap these changes with a check on a boolean "editing" flag so the recursive calls skip over and simply return while the changes that come from within.

like image 38
Timo Ohr Avatar answered Oct 14 '22 14:10

Timo Ohr