I use TextWatcher to handle the EditText field in android but it shows $ 12.50 how would it be without the "$"?

0
public class MoneyTextWatcher implements TextWatcher {
    private final WeakReference<EditText> editTextWeakReference;
    private final Locale locale;

    public MoneyTextWatcher(EditText editText, Locale locale) {
        this.editTextWeakReference = new WeakReference<EditText>(editText);
        this.locale = locale != null ? locale : Locale.getDefault();
    }

    public MoneyTextWatcher(EditText editText) {
        this.editTextWeakReference = new WeakReference<EditText>(editText);
        this.locale = Locale.getDefault();
    }

    @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) {
        EditText editText = editTextWeakReference.get();
        if (editText == null) return;
        editText.removeTextChangedListener(this);

        BigDecimal parsed = parseToBigDecimal(editable.toString(), locale);
        String formatted = NumberFormat.getCurrencyInstance(locale).format(parsed);

        editText.setText(formatted);
        editText.setSelection(formatted.length());
        editText.addTextChangedListener(this);
    }

    private BigDecimal parseToBigDecimal(String value, Locale locale) {
        String replaceable = String.format("[%s,.\s]", NumberFormat.getCurrencyInstance(locale).getCurrency().getSymbol());

        String cleanString = value.replaceAll(replaceable, "");

        return new BigDecimal(cleanString).setScale(
            2, BigDecimal.ROUND_FLOOR).divide(new BigDecimal(100), BigDecimal.ROUND_FLOOR
        );
    }
}

//Codigo do editText
Locale mLocale = new Locale("pt", "BR");
mEditTextValorParc.addTextChangedListener(new MoneyTextWatcher(mEditTextValorParc, mLocale));
    
asked by anonymous 04.10.2017 / 00:13

2 answers

0

As mentioned, there is no need for this TextWatcher if you do not want the R $. But for more clarification the Locale and getCurrencyInstance method has great relevance for the display of R $.

Locale is used to set the desired country or region, and getCurrencyInstance will adopt the currency according to Locale.

    
04.10.2017 / 02:26
0

Change the line

String replaceable = String.format("[%s,.\s]", NumberFormat.getCurrencyInstance(locale).getCurrency().getSymbol());

for

String formatted = NumberFormat.getCurrencyInstance(locale).format(parsed).replace("R","").replace("$","");
    
26.09.2018 / 23:36