我在Android应用程序中工作,我想在android中为editText创建一个小数掩码。我想要一个像maskMoney jQuery插件的面具。但在某些情况下,我的号码将有2位小数,3位小数或将是一个整数。我想做这样的事情:
最好的方法是什么?
答案 0 :(得分:-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) {}
};
}