android 的 EditText 十进制掩码
EditText decimal mask for android
我在 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
最好的方法是什么?
我解决了这个问题:
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) {}
};
}
我在 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
最好的方法是什么?
我解决了这个问题:
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) {}
};
}