在开发中EditText总会要求输入限制,数字?个数?几行?
1.在限制输入类型为double的数字时就需要做两步判断,
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:numeric="decimal" />
在布局中定义EditText的时候设置为只能输入数字,设置数字的时候可以直接设置android:numeric="decimal" ;
然后再进行具体判断
/**
* 判断字符串是否是数字
*/
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,在输入的时候进行判断
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);
}
}
};
希望能帮助到小伙伴们……