我有一个带有单个数字十进制EditText的应用。我想这样,用户不能输入大于120.0的值。我不知道该怎么做。但是,我能够输入从1到120的数字(没有小数)。
这是我的代码:
edittext.setFilters(new InputFilter[] {new InputFilterMinMax(1,120)});
public class InputFilterMinMax implements InputFilter {
private int min, max;
public InputFilterMinMax(int min, int max) {
this.min = min;
this.max = 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;
}
}
答案 0 :(得分:0)
这是一个可以给你结果的课程,请在下面找到代码
package Utils;
import android.text.InputFilter;
import android.text.Spanned;
public class InputFilterMinMax implements InputFilter {
private Float min, max;
public InputFilterMinMax(int min, int max) {
this.min = min;
this.max = max;
}
public InputFilterMinMax(Float min, Float max) {
this.min = Float.parseFloat(min);
this.max = Float.parseFloat(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 {
Float input = Float.parseFloat(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;
}
}
您可以将此类用作以下代码:
editText.setFilters(new InputFilter[]{ new InputFilterMinMax("1", "120")});
快乐编码:)