Error clear Textwatcher field

Asked

Viewed 61 times

-1

Staff use the TextWacher in the EditText, works perfectly and when I finish the registration I put campo.setText(""); it does not clean, close the application and shows an error.

my class TextWatcher:

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

The call on Edit:

txtValorRecarga.addTextChangedListener(new MoneyTextWatcher(txtValorRecarga, mLocale));

And as I am cleaning in another method after the completion of the form submission:

txtValorRecarga.setText("");

If anyone can help.

1 answer

-1


You can try this:

editText.removeTextChangedListener(yourTextWatcher);
  • editText is already my Edit, and yourTextWatcher what it would be?

  • yourTextWatcher would be your editTextWeakReference

Browser other questions tagged

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