針對(duì)輸入框輸入金額有效位數(shù)限制
/**
* EditText 數(shù)字輸入范圍過(guò)濾 (0 <= ? < MAX_VALUE && 小數(shù)點(diǎn)后保留 POINTER_LENGTH 位)
*
* @author gavin.xiong 2016/12/21
*/
public class NumRangeInputFilter implements InputFilter {
// 只允許輸入數(shù)字和小數(shù)點(diǎn)
private static final String REGEX = "([0-9]|\\.)*";
// 輸入的最大金額
private static final int MAX_VALUE = 100000;
// 小數(shù)點(diǎn)后的位數(shù)
private static final int POINTER_LENGTH = 2;
private static final String POINTER = ".";
private static final String ZERO_ZERO = "00";
/**
* @param source 新輸入的字符串
* @param start 新輸入的字符串起始下標(biāo),一般為0
* @param end 新輸入的字符串終點(diǎn)下標(biāo),一般為source長(zhǎng)度-1
* @param dest 輸入之前文本框內(nèi)容
* @param dstart 原內(nèi)容起始坐標(biāo),一般為0
* @param dend 原內(nèi)容終點(diǎn)坐標(biāo),一般為dest長(zhǎng)度-1
* @return 輸入內(nèi)容
*/
@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
String sourceText = source.toString();
String destText = dest.toString();
// 新輸入的字符串為空(刪除剪切等)
if (TextUtils.isEmpty(sourceText)) {
return "";
}
// 拼成字符串
String temp = destText.substring(0, dstart)
+ sourceText.substring(start, end)
+ destText.substring(dend, dest.length());
Log.v("temp", "-" + temp);
// 純數(shù)字加小數(shù)點(diǎn)
if (!temp.matches(REGEX)) {
Log.d("TAG", "!純數(shù)字加小數(shù)點(diǎn)");
return dest.subSequence(dstart, dend);
}
// 小數(shù)點(diǎn)的情況
if (temp.contains(POINTER)) {
// 第一位就是小數(shù)點(diǎn)
if (temp.startsWith(POINTER)) {
Log.d("TAG", "第一位就是小數(shù)點(diǎn)");
return dest.subSequence(dstart, dend);
}
// 不止一個(gè)小數(shù)點(diǎn)
if(temp.indexOf(POINTER) != temp.lastIndexOf(POINTER)) {
Log.d("TAG", "不止一個(gè)小數(shù)點(diǎn)");
return dest.subSequence(dstart, dend);
}
}
double sumText = Double.parseDouble(temp);
if (sumText >= MAX_VALUE) {
// 超出最大值
Log.d("TAG", "超出最大值");
return dest.subSequence(dstart, dend);
}
// 有小數(shù)點(diǎn)的情況下
if (temp.contains(POINTER)) {
//驗(yàn)證小數(shù)點(diǎn)精度,保證小數(shù)點(diǎn)后只能輸入兩位
if (!temp.endsWith(POINTER) && temp.split("\\.")[1].length() > POINTER_LENGTH) {
Log.d("TAG", "保證小數(shù)點(diǎn)后只能輸入兩位");
return dest.subSequence(dstart, dend);
}
} else if (temp.startsWith(POINTER) || temp.startsWith(ZERO_ZERO)) {
// 首位只能有一個(gè)0
Log.d("TAG", "首位只能有一個(gè)0");
return dest.subSequence(dstart, dend);
}
Log.d("TAG", "正常情況");
return source;
}
}
在代碼中設(shè)置
editText.setFilters(new InputFilter[]{new NumRangeInputFilter()});