您的位置:首页 > 其它

Edittext判断输入是否为数字(包含小数点)

2016-12-12 18:39 411 查看
在开发中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);
}
}
};


希望能帮助到小伙伴们……
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: