在APP中用到Edittext的时候经常会遇到输入限制的问题,
1.在限制输入类型为double的数字时就需要做两步判断,
<EditText android:layout_width="wrap_content" android:layout_height="wrap_content" android:numeric="decimal" />在布局中定义EditText的时候设置为只能输入数字,设置数字的时候可以直接设置android:numeric="decimal" ,或者设置android:digits=".0123456789".
第一种设置在输入内容为 .12的时候获取出来的值会默认为0.12,第二种则可以输入....12这样的内容,这时候就需要手动判断输入内容是否位数字。方法下,所以一般直接用第一种
/** * 判断字符串是否是数字 */ public static boolean isNumber(String value) { return isInteger(value) || isDouble(value); } /** * 判断字符串是否是整数 */ public static boolean isInteger(String value) { try { Integer.parseInt(value); return true; } catch (NumberFormatException e) { return false; } } /** * 判断字符串是否是浮点数 */ public static boolean isDouble(String value) { try { Double.parseDouble(value); if (value.contains(".")) return true; return false; } catch (NumberFormatException e) { return false; } }
2.限制输入小数位数
需要给EditText设置TextWatcher,在输入的时候进行判断,下面为限制输入4位小数,其它同理
TextWatcher mTextWatcher = new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void afterTextChanged(Editable s) { String temp = s.toString(); int posDot = temp.indexOf("."); if (posDot <= 0) return; if (temp.length() - posDot - 1 > 4) { s.delete(posDot + 5, posDot + 6); } } };