EditTextView 限制輸入
public class NumberInputFilter implements InputFilter {
/**
* 最大數(shù)字
*/
public double MAX_VALUE = 9999999;
/**
* 最小數(shù)
*/
public double MIN_VALUE = 0;
/**
* 小數(shù)點(diǎn)后的數(shù)字的位數(shù)
*/
public int POINTER_LENGTH = 2;
private static final String POINTER = ".";
Pattern p;
public NumberInputFilter() {
//用于匹配輸入的是0-9 . 這幾個(gè)數(shù)字和字符
p = Pattern.compile("([0-9]|\\.)*");
}
/**
* @param max 最大數(shù)
* @param length 小數(shù)點(diǎn)位數(shù)
*/
public NumberInputFilter(double max, int length) {
MAX_VALUE = max;
POINTER_LENGTH = length;
//用于匹配輸入的是0-9 . 這幾個(gè)數(shù)字和字符
p = Pattern.compile("([0-9]|\\.)*");
}
/**
* @param max 最大數(shù)
* @param min 最小數(shù)(length=0時(shí)生效)
* @param length 小數(shù)點(diǎn)位數(shù)
*/
public NumberInputFilter(double max, double min, int length) {
MAX_VALUE = max;
MIN_VALUE = min;
POINTER_LENGTH = length;
if (length == 0) {
//用于匹配輸入的是0-9 . 這幾個(gè)數(shù)字和字符
p = Pattern.compile("([0-9])*");
} else {
p = Pattern.compile("([0-9]|\\.)*");
}
}
/**
* source 新輸入的字符串
* start 新輸入的字符串起始下標(biāo),一般為0
* end 新輸入的字符串終點(diǎn)下標(biāo)臣嚣,一般為source長(zhǎng)度-1
* dest 輸入之前文本框內(nèi)容
* dstart 原內(nèi)容起始坐標(biāo),一般為0
* dend 原內(nèi)容終點(diǎn)坐標(biāo),一般為dest長(zhǎng)度-1
*/
@Override
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend) {
//驗(yàn)證刪除等按鍵
if (TextUtils.isEmpty(source)) {
return "";
}
Matcher matcher = p.matcher(source);
if (!matcher.matches()) {
return "";
}
//已經(jīng)輸入小數(shù)點(diǎn)的情況下谓着,只能輸入數(shù)字
if (dest.toString().contains(POINTER)) {
if (POINTER.contentEquals(source)) { //只能輸入一個(gè)小數(shù)點(diǎn)
return "";
}
//驗(yàn)證小數(shù)點(diǎn)精度,保證小數(shù)點(diǎn)后只能輸入多少位
int index = dest.toString().indexOf(POINTER);
int length = dest.toString().substring(index).length();
// dstart > index 輸入位置在原點(diǎn)之后途凫,
if (dstart > index && length == POINTER_LENGTH + 1) {
return "";
}
} else {
//限制小數(shù)點(diǎn)位數(shù)
if (POINTER_LENGTH > 0) {
if (source.equals(POINTER) && dest.toString().length() == 0) {
return "0.";
}
} else {
if (source.equals(POINTER)) {
return "";
}
}
}
//限制大小
String inputStr = dest.toString().substring(0, dstart) + source + dest.toString().substring(dstart, dest.length());
double input = Double.parseDouble(inputStr);
if (isInRange(MIN_VALUE, MAX_VALUE, input)) {
return null;
} else {
if (POINTER_LENGTH > 0 && (inputStr.equals("0.0") || inputStr.equals("0.00"))) { // 忽略0.0 0.00等情況
return null;
}
}
return "";
}
private boolean isInRange(double a, double b, double c) {
return b > a ? c >= a && c <= b : c >= b && c <= a;
}
}