I am using edit text in my code.I need to limit the weight value to 160 .How to achieve this.
This is the XML I'm using
android:id="@+id/txtWeight" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="5dp" android:inputType="number" android:layout_weight="0" android:background="@drawable/border" android:padding="5dp" android:maxLength="3" android:textSize="15sp" android:maxLines="1" android:hint=""
i have taken maxLenght as "3". So user will have option of entering upto 999 . I need to limit to 160.
Try this:
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 {
int input = Integer.parseInt(dest.toString() + source.toString());
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;
}
}
Then on your fragment / activity:
EditText et = (EditText) findViewById(R.id.myEditText);
et.setFilters(new InputFilter[]{ new InputFilterMinMax("1", "180")});