本篇文章转载自冯丰枫《Android EditText 小数输入优化》。大神使用正则表达式加TextWatcher对EditText小数输入进行限制,感觉比使用filter要方便很多,代码更加简洁,可读性更高。
先看一下作者的演示gif:
在需要做限制的EditText上add下面的TextWatcher就好:
public class DecimalInputTextWatcher implements TextWatcher {
private Pattern mPattern;
/**
* 不限制整数位数和小数位数
*/
public DecimalInputTextWatcher() {
}
/**
* 限制整数位数或着限制小数位数
*
* @param type 限制类型
* @param number 限制位数
*/
public DecimalInputTextWatcher(Type type, int number) {
if (type == Type.decimal) {
mPattern = Pattern.compile("^[0-9]+(\\.[0-9]{0," + number + "})?$");
} else if (type == Type.integer) {
mPattern = Pattern.compile("^[0-9]{0," + number + "}+(\\.[0-9]{0,})?$");
}
}
/**
* 既限制整数位数又限制小数位数
*
* @param integers 整数位数
* @param decimals 小数位数
*/
public DecimalInputTextWatcher(int integers, int decimals) {
mPattern = Pattern.compile("^[0-9]{0," + integers + "}+(\\.[0-9]{0," + decimals + "})?$");
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable editable) {
String text = editable.toString();
if (TextUtils.isEmpty(text)) return;
// 删除首位无效的“0”
if ((editable.length() > 1) && (editable.charAt(0) == '0') && editable.charAt(1) != '.') {
editable.delete(0, 1);
return;
}
// 首位是“.”自动补“0”
if (text.equals(".")) {
editable.insert(0, "0");
return;
}
if (mPattern != null && !mPattern.matcher(text).matches() && editable.length() > 0) {
editable.delete(editable.length() - 1, editable.length());
}
}
public enum Type {
integer, decimal
}
}