關(guān)于金額的輸入需要考慮以下幾種情況
- 過濾除了小數(shù)點(diǎn)和數(shù)字的其他字符
- 第一個(gè)字符是小數(shù)點(diǎn)前面需要補(bǔ)0,小數(shù)點(diǎn)只能輸入兩位
- 第一個(gè)字符是大于0的數(shù)字,整數(shù)部分最多可以輸入9位
- 第一個(gè)字符是等于0的字符,第二個(gè)數(shù)字必須是小數(shù)點(diǎn)
- 小數(shù)點(diǎn)只能輸入一個(gè)
使用:
MoneyEditUtils .afterDotTwo(mEditText);
public class MoneyEditUtils {
private static DecimalFormat df = new DecimalFormat("#0.00");
public static void afterDotTwo(final EditText editText) {
editText.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
String money = s.toString();
try {
if (TextUtils.isEmpty(money)) {
money = "0.00";
} else {
money = df.format(Double.valueOf(money));
}
} catch (NumberFormatException e) {
//避免輸入多余的小數(shù)點(diǎn)
editText.setText(money.substring(0, money.length() - 1));
editText.setSelection(editText.length());
}
if (s.toString().contains(".")) {
if (s.toString().indexOf(".") > 9) {
s = s.toString().subSequence(0, 9) + s.toString().substring(s.toString()
.indexOf("."));
editText.setText(s);
editText.setSelection(9);
}
} else {
if (s.toString().length() > 9) {
s = s.toString().subSequence(0, 9);
editText.setText(s);
editText.setSelection(9);
}
}
// 判斷小數(shù)點(diǎn)后只能輸入兩位
if (s.toString().contains(".")) {
if (s.length() - 1 - s.toString().indexOf(".") > 2) {
s = s.toString().subSequence(0,
s.toString().indexOf(".") + 3);
editText.setText(s);
editText.setSelection(s.length());
}
}
//如果第一個(gè)數(shù)字為0,第二個(gè)不為點(diǎn),就不允許輸入
if (s.toString().startsWith("0") && s.toString().trim().length() > 1) {
if (!s.toString().substring(1, 2).equals(".")) {
editText.setText(s.subSequence(0, 1));
editText.setSelection(1);
}
}
//如果第一個(gè)輸入的為點(diǎn),自動(dòng)在前面加0 要不會(huì)閃退
if (s.toString().startsWith(".")) {
editText.setText("0.");
editText.setSelection(2);
}
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void afterTextChanged(Editable s) {
if (!editText.getText().toString().trim().equals("")) {
if (editText.getText().toString().trim().substring(0, 1).equals(".")) {
editText.setText(String.format("0%s", editText.getText().toString().trim
()));
editText.setSelection(1);
}
}
}
});
}
}