**指我有一个带有提示0.00的编辑文本
Now i want to input text If i press 5 it should appear 0.05 next if i press 4 it should come like 0.54**
答案 0 :(得分:0)
这是完整的解决方案。 试试这个
private String current = "";
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if(!s.toString().equals(current)){
[your_edittext].removeTextChangedListener(this);
String cleanString = s.toString().replaceAll("[$,.]", "");
double parsed = Double.parseDouble(cleanString);
String formated = NumberFormat.getCurrencyInstance().format((parsed/100));
current = formated;
[your_edittext].setText(formated);
[your_edittext].setSelection(formated.length());
[your_edittext].addTextChangedListener(this);
}
}
答案 1 :(得分:0)
这是我的要求的正确答案
public static void decimalFormat(final EditText editText) {
editText.addTextChangedListener(new TextWatcher() {
String before = "";
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
before = s.toString();
}
@Override
public void afterTextChanged(Editable s) {
if (!before.equalsIgnoreCase(s.toString())
&& !TextUtils.isEmpty(s.toString().trim())) {
before = s.toString();
String tvStr = s.toString();
if (tvStr.contains("-") || tvStr.equals(".")) {
editText.setText("");
}
if (!tvStr.equals("") && !tvStr.equals(".")) {
String cleanString = getFormatedNumber(tvStr, 2);
editText.setText(cleanString);
try {
editText.setSelection(cleanString.length());
return;
} catch (IndexOutOfBoundsException e) {
editText.setSelection(cleanString.length() - 1);
return;
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
});
}
public static String getFormatedNumber(String text,int decimalPoint){
String cleanString = text.replaceAll("[,.|\\s]", "");
if (TextUtils.isEmpty(cleanString)) {
return "0.00";
}
NumberFormat formatter = new DecimalFormat("#,##0.00");
double number = Double.parseDouble(cleanString) / (long) Math.pow(10.0, decimalPoint);
return formatter.format(number).toString();
}