我有EditText
,我用它来输入百分比值。我限制用户输入的值不能超过100,并且可以正常工作。我也可以按百分比输入分数部分,但小数点(。)后只能输入两位数字,即99.95
我希望它能以编程方式实现,因为我在每次都会用到输入值和在其他字段中进行更改的弹出窗口中使用此EditText
。我尝试按照以下代码来实现我的目标。
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")});
}
我正在使用过滤器类将其转换为百分比,请参见以下代码:
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;
}
}
如何设置EditText
中的分数限制?
答案 0 :(得分:1)
在进行一些更改后,您可以按以下方式使用输入过滤器:
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);
}
}
}
答案 1 :(得分:0)
使用edittext的maxLength
属性,
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Customization"
android:maxLength="4"
android:singleLine="true"
/>