Hexar 的答案很有用,但是当用户删除所有数字或移动光标时,它缺乏错误检测。我以他的回答和此处的回答为基础,形成了一个完整的解决方案。由于在 onTextChanged() 方法中设置了 EditText,这可能不是最佳实践,但它可以工作。
/* don't allow user to move cursor while entering price */
mEditText.setMovementMethod(null);
mEditText.addTextChangedListener(new TextWatcher() {
private String current = "";
NumberFormat formatter = NumberFormat.getCurrencyInstance();
private double parsed;
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (!s.toString().equals(current)) {
/* remove listener to prevent stack overflow from infinite loop */
mEditText.removeTextChangedListener(this);
String cleanString = s.toString().replaceAll("[$,]", "");
try {
parsed = Double.parseDouble(cleanString);
}
catch(java.lang.NumberFormatException e) {
parsed = 0;
}
formatter.setMaximumFractionDigits(0);
String formatted = formatter.format(parsed);
current = formatted;
mEditText.setText(formatted);
/* add listener back */
mEditText.addTextChangedListener(this);
/* print a toast when limit is reached... see xml below.
* this is for 6 chars */
if (start == 7) {
Toast toast = Toast.makeText(getApplicationContext(),
"Maximum Limit Reached", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
}
}
确保用户不输入无效信息的一种快速方法是编辑 xml。对于我的程序,设置了 6 个数字字符的限制。
<!-- it says maxLength 8 but it's really 6 digits and a '$' and a ',' -->
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number|textVisiblePassword"
android:maxLength="8"
android:digits="0123456789"
android:id="@+id/mEditText"
android:hint="Price"/>