Use the Textwatcher to handle the Edittext field on android but it shows $ 12,50 as it would be without the "R$"?

Asked

Viewed 662 times

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));
  • 1

    What is "treat"? Why are you using a Textwatcher for money if you don’t want the cash symbol?

  • In fact I only need a mask for monetary value in an editText, real in case you format this way to save in the database "20.99" if you have any example of how to do

3 answers

0


As it was commented there is no need for this Textwatcher if you do not want the R$. But for further clarification the Locale and the getCurrencyInstance method have great relevance to the R display$.

Locale serves to set the desired country or region and getCurrencyInstance will adopt the monetary unit according to Locale.

0

you can see this link https://gist.github.com/webkoder/0acc7d00814d901af74dcdf7db2b4faf

// Uso:
// Declarar um objeto TextWatcher

// O valor do TextWatcher é o retorno da função Mask.insert, com dois parametros: string com o formato da mascara e a caixa de texto que irá receber a mascara

// ou o retorno da função Mask.monetario, apenas com a caixa de texto que será receberá o valor monetario

// Adicionar na caixa de texto o evento TextWatcher

// Ex:

// TextWatcher cpfMask = Mask.insert("###.###.###-##, editCpf);

// cpfMask.addTextChangedListener(editCpf)

// TextWatcher salarioMask = Mask.monetario(editSalario);

// salarioMask.addTextChangedListener(editSalario);


package [package];

import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;

public abstract class Mask {
    public static String unmask(String s) {
        return s.replaceAll("[.]", "").replaceAll("[-]", "")
                .replaceAll("[/]", "").replaceAll("[(]", "")
                .replaceAll("[)]", "");
    }

    public static TextWatcher insert(final String mask, final EditText ediTxt) {
        return new TextWatcher() {
            boolean isUpdating;
            String old = "";

            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
                String str = Mask.unmask(s.toString());
                String mascara = "";
                if (isUpdating) {
                    old = str;
                    isUpdating = false;
                    return;
                }
                int i = 0;
                for (char m : mask.toCharArray()) {
                    if (m != '#' && str.length() > old.length()) {
                        mascara += m;
                        continue;
                    }
                    try {
                        mascara += str.charAt(i);
                    } catch (Exception e) {
                        break;
                    }
                    i++;
                }
                isUpdating = true;
                ediTxt.setText(mascara);
                ediTxt.setSelection(mascara.length());
            }

            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
            }

            public void afterTextChanged(Editable s) {
            }
        };
    }

    public static TextWatcher monetario(final EditText ediTxt) {
        return new TextWatcher() {
            // Mascara monetaria para o preço do produto
                private String current = "";
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) { }

                @Override
                public void afterTextChanged(Editable s) { }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                    if(!s.toString().equals(current)){
                        ediTxt.removeTextChangedListener(this);

                        String cleanString = s.toString().replaceAll("[R$,.]", "");

                        double parsed = Double.parseDouble(cleanString);
                        String formatted = NumberFormat.getCurrencyInstance().format((parsed/100));

                        current = formatted.replaceAll("[R$]", "");
                        ediTxt.setText(current);
                        ediTxt.setSelection(current.length());

                        ediTxt.addTextChangedListener(this);
                    }
                }

        };
    }
}

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("$","");

Browser other questions tagged

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