import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextUtils;
import android.widget.EditText;
public class EditTextNumberHelper {
private static final int MAX_INTEGER = 9999999;
private static final int MAX_DECIMAL = 2;
/**
* 设置EditText只能输入数字,小数点前最大99999999,小数点后最多两位
*/
public static void configNumberEditText(EditText editText) {
editText.setInputType(android.text.InputType.TYPE_CLASS_NUMBER
| android.text.InputType.TYPE_NUMBER_FLAG_DECIMAL);
InputFilter[] filters = new InputFilter[]{
new NumberInputFilter()
};
editText.setFilters(filters);
}
/**
* 获取EditText中的数值,如果为空返回0
*/
public static double getNumberValue(EditText editText) {
String text = editText.getText().toString();
if (TextUtils.isEmpty(text)) {
return 0;
}
try {
return Double.parseDouble(text);
} catch (NumberFormatException e) {
return 0;
}
}
/**
* 设置数值
*/
public static void setNumberValue(EditText editText, double value) {
if (value < 0) {
value = 0;
}
if (value > MAX_INTEGER) {
value = MAX_INTEGER;
}
// 保留两位小数
String formatted = String.format("%.2f", value);
// 去除末尾多余的0
if (formatted.contains(".")) {
formatted = formatted.replaceAll("0*$", "").replaceAll("\\.$", "");
}
editText.setText(formatted);
}
/**
* 自定义输入过滤器
*/
static class NumberInputFilter implements InputFilter {
@Override
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend) {
if (TextUtils.isEmpty(source)) {
return null;
}
String oldContent = dest.toString();
String newContent = oldContent.substring(0, dstart)
+ source.subSequence(start, end)
+ oldContent.substring(dend);
if (TextUtils.isEmpty(newContent)) {
return null;
}
if (newContent.equals(".")) {
return "0.";
}
// 允许数字和小数点
if (!newContent.matches("\\d*\\.?\\d*")) {
return "";
}
// 不允许多个小数点
if (newContent.indexOf('.') != newContent.lastIndexOf('.')) {
return "";
}
String[] parts = newContent.split("\\.");
String integerPart = parts[0];
String decimalPart = parts.length > 1 ? parts[1] : "";
// 处理前导零
if (!TextUtils.isEmpty(integerPart) && integerPart.length() > 1 && integerPart.startsWith("0")) {
String newInteger = integerPart.replaceFirst("^0+", "");
if (TextUtils.isEmpty(newInteger)) {
newInteger = "0";
}
if (decimalPart.isEmpty()) {
return newInteger;
} else {
return newInteger + "." + decimalPart;
}
}
// 检查整数部分大小
if (!TextUtils.isEmpty(integerPart) && integerPart.length() > 0) {
try {
long intValue = Long.parseLong(integerPart);
if (intValue > MAX_INTEGER) {
return "";
}
} catch (NumberFormatException e) {
return "";
}
}
// 检查小数位数
if (decimalPart.length() > MAX_DECIMAL) {
return "";
}
return null;
}
}
}
使用方法
EditTextNumberHelper.configNumberEditText(priceEt.getView());

1524

被折叠的 条评论
为什么被折叠?



