Coin mask on the field

Asked

Viewed 3,604 times

0

I would like to create masks in my android number field.
I’ve already managed to add the mask ###,##.
But this is not a good practice, because if I want to add a value of R $ 1,000,00 the field does not accept.
Has anyone there ever been there ?

1 answer

8

Arthur, I have a class TextWatcherthat I use in my project, see if it suits you:

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
        );
    }
}

In his EditText add the TextWatcher:

Locale mLocale = new Locale("pt", "BR");
mEditTextValorParc.addTextChangedListener(new MoneyTextWatcher(mEditTextValorParc, mLocale));

In this case, it will format the EditText as the user enters the numbers, as happens in a credit card machine. If he type for example the number 2, would be 0,02, if right after he typed the 1, it would 0,21, and so on.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.