【问题标题】:EditText decimal mask for androidandroid的EditText十进制掩码
【发布时间】:2015-12-13 09:09:06
【问题描述】:
我正在使用 Android 应用程序,我想在 android 中为 editText 创建一个十进制掩码。我想要一个像 maskMoney jQuery 插件这样的面具。但在某些情况下,我的号码会有 2 个小数位、3 个小数位或整数。我想做这样的事情:
- EditText 创建时,带有默认值:00.01
- 如果用户按数字 2,结果应该是:00.12
- 如果用户按数字 3,结果应该是:01.23
- 如果用户按数字 4,结果应该是:12.34
- 如果用户按数字 5,结果应该是:123.45
- 如果用户按数字 6,结果应该是:1,234.56
最好的方法是什么?
【问题讨论】:
标签:
java
android
android-edittext
masking
【解决方案1】:
我解决了这个问题:
public static TextWatcher amount(final EditText editText, final String metric) {
return new TextWatcher() {
String current = "";
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (!s.toString().equals(current)) {
editText.removeTextChangedListener(this);
String cleanString = s.toString();
if (count != 0) {
String substr = cleanString.substring(cleanString.length() - 2);
if (substr.contains(".") || substr.contains(",")) {
cleanString += "0";
}
}
cleanString = cleanString.replaceAll("[,.]", "");
double parsed = Double.parseDouble(cleanString);
DecimalFormat df = new DecimalFormat("0.00");
String formatted = df.format((parsed / 100));
current = formatted;
editText.setText(formatted);
editText.setSelection(formatted.length());
editText.addTextChangedListener(this);
}
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
public void afterTextChanged(Editable s) {}
};
}