I have EditText
, I use it to enter percentage value. I put restrict that user can not enter value more than 100 and it's works fine. I'm also allowed to enter fraction part in percentage, But allow only two digit after decimal point (.) i.e. 99.95
I want it to achieve programmatically because I use this EditText
in the popup that uses every time to enter value and change in other field. I have tried following code to achieve my thing.
if (title.contains("Deposit")) {
edt_get_value_popup_value.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL | InputType.TYPE_NUMBER_FLAG_SIGNED);
edt_get_value_popup_value.setFilters(new InputFilter[]{new InputFilterMinMax("1", "100")});
}
I'm using filter class to convert into percentage, see following code:
public class InputFilterMinMax implements InputFilter {
private Float min, max;
public InputFilterMinMax(Float min, Float max) {
this.min = min;
this.max = max;
}
public InputFilterMinMax(String min, String max) {
this.min = Float.parseFloat(min);
this.max = Float.parseFloat(max);
}
@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
try {
Float input = Float.parseFloat(dest.toString() + source.toString());
if (isInRange(min, max, input)) return null;
} catch (NumberFormatException nfe) {
}
return "";
}
private boolean isInRange(Float a, Float b, Float c) {
return b > a ? c >= a && c <= b : c >= b && c <= a;
}
}
How can I set limit of fraction part in EditText
?
you can use input filter as below after applying some changes:
public class InputFilterMinMax implements InputFilter {
private Float min, max;
public InputFilterMinMax(Float min, Float max) {
this.min = min;
this.max = max;
}
public InputFilterMinMax(String min, String max) {
this.min = Float.parseFloat(min);
this.max = Float.parseFloat(max);
}
@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
try {
Float input = Float.parseFloat(dest.toString() + source.toString());
String inputValue = (dest.toString() + source.toString());
if (isInRange(min, max, input, inputValue)) return null;
} catch (NumberFormatException nfe) {
}
return "";
}
private boolean isInRange(Float min, Float max, Float input, String inputValue) {
if (inputValue.contains(".") && (inputValue.split("\\.").length > 1)) {
return (max > min ? input >= min && input <= max : input >= max && input <= min) && (inputValue.split("\\.")[1].length() < 3);
} else {
return (max > min ? input >= min && input <= max : input >= max && input <= min);
}
}
}