首先,xml中EditText设置属性:
android:inputType="numberDecimal"
然后设置公有变量:
private BigDecimal totalAmount;
private String totalAmountStr;
private boolean flag = true;
其中flag是为了预防在TextChangeListener中更改EditText内容时产生死循环用的,不懂得就直接复制代码吧
最后Java文件中给EditText设置TextChangeListener:
edt.addTextChangedListener(new TextWatcher() {
@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 s) {
if (!TextUtils.isEmpty(s.toString()) && flag) {
BigDecimal result;
String temp = s.toString();
int posDot = temp.indexOf(".");
try {
if (posDot == s.length() - 1) {
return;
}
result = new BigDecimal(s.toString());
} catch (Exception e) {
return;
}
//不允许超出最大值
if (result.compareTo(totalAmount) == 1) {
temp = totalAmountStr;
ToastUtils.show("当前最多转出" + totalAmountStr + "元");
}
//保留两位小数
flag = false;
s.clear();
if (posDot > 0 && temp.length() - posDot - 1 > 2) {
temp = temp.substring(0, posDot + 3);
}
s.append(temp);
flag = true;
}
}
});