我想将美元符号删除到我的金额格式化程序,但它不起作用我已经分配了替换它包含一个美元符号。我怎么能这样做?
这是我的Text Watcher代码。
NumberFormat canadaEnglish = NumberFormat.getCurrencyInstance(Locale.CANADA);
public class MoneyTextWatcher implements TextWatcher {
private final WeakReference<EditText> editTextWeakReference;
boolean hasFractionalPart = false;
private EditText editText;
public MoneyTextWatcher(EditText editText) {
editTextWeakReference = new WeakReference<EditText>(editText);
this.editText = editText;
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
if (s.toString().contains(String.valueOf(df.getDecimalFormatSymbols().getDecimalSeparator()))) {
hasFractionalPart = true;
} else {
hasFractionalPart = false;
}
if (mIsInWatcher)
return;
mIsInWatcher = true;
}
@Override
public void afterTextChanged(Editable editable) {
if (editText == null)
return;
String s = editable.toString();
editText.removeTextChangedListener(this);
String cleanString = s.toString().replaceAll("[$,.]", "");
String formatted = "";
System.out.println(cleanString);
BigDecimal parsed = new BigDecimal(cleanString).setScale(2,BigDecimal.ROUND_FLOOR).divide(new BigDecimal(100),BigDecimal.ROUND_FLOOR);
formatted = canadaEnglish.format(parsed).replace("\\$",pesoCurrency);
System.out.println("formatted > " + formatted);
String trimFormatted = formatted.replace("\\$", pesoCurrency);
System.out.println("trimFormatted > " + trimFormatted);
editText.setText(formatted.replace("\\$", ""));
editText.setSelection(formatted.length());
editText.addTextChangedListener(this);
}
}
答案 0 :(得分:0)
试试这个:
String charToReplace = new String[]{"[","$",",",".","]"};
for(String s: charToReplace)
cleanString = cleanString .replace(s,"");
答案 1 :(得分:0)
这是我的MoneyTextWatcher ..感谢响应DroidWorm ..我只需要使用replaceAll(args ..,args ..)从我的edittext中分配文本而不是替换(args ..,args ..)
public static class MoneyTextWatcher implements TextWatcher {
private EditText editText;
public MoneyTextWatcher(EditText editText) {
this.editText = editText;
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
}
@Override
public void afterTextChanged(Editable editable) {
String formatted = "";
if (editText == null)
return;
String s = editable.toString();
editText.removeTextChangedListener(this);
String cleanString = s.toString().replaceAll("[\u20B1,]", "");
System.out.println("cleanString > " + cleanString);
BigDecimal parsed = new BigDecimal(cleanString.equals("") ? "0.00"
: cleanString).setScale(2, BigDecimal.ROUND_FLOOR).divide(
new BigDecimal(100), BigDecimal.ROUND_FLOOR);
formatted = canadaEnglish.format(parsed)
.replaceAll("\\$", CURRENCY);
//System.out.println("formatted > " + formatted);
editText.setText(formatted.replace("\\$", ""));
editText.setSelection(formatted.length());
editText.addTextChangedListener(this);
}
}