how to put monetary mask for EditText in an Android application?

1

How to put monetary mask for EditText in an Android application only with numeric values without the R $, that is, to print in EditText 2.99? If you have an example.

    
asked by anonymous 14.11.2017 / 12:46

2 answers

1

You can use this lib: link

Then just add edittext with mascara in xml:

 <com.santalu.maskedittext.MaskEditText
android:id="@+id/et_phone_number"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/hint_phone_number"
android:inputType="number"
app:mask="#,##"/>
    
14.11.2017 / 13:05
1

Modify the onChanged of TextEdit via code that works. And you do not even need a mask for that. Here is an example:

        seu_text_edit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            private String current = "";
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if(!s.toString().equals(current)) {
                    Locale myLocale = new Locale("pt", "BR");
                    //Nesse bloco ele monta a maskara para money
                    txtUnitario.removeTextChangedListener(this);
                    String cleanString = s.toString().replaceAll("[R$,.]", "");
                    Decimal parsed = Double.parseDouble(cleanString);
                    String formatted = NumberFormat.getCurrencyInstance(myLocale).format((parsed / 100));
                    current = formatted;
                    txtUnitario.setText(formatted);
                    txtUnitario.setSelection(formatted.length());

                    //Nesse bloco ele faz a conta do total (Caso a qtde esteja preenchida)
                    String qtde = txtQtdeLitros.getText().toString();

                    txtUnitario.addTextChangedListener(this);
                }
            }
            @Override
            public void afterTextChanged(Editable s) {

            }
        });

This is just a basic way to make a monetary field, there are many other ways to do and in my opinion, this type of field does not need to mask because you just tell it is currency type and treat the data using Decimal (Always avoid working with Double or Float values when monetary). Detail, Using this logic instead of a mask you will also give a super cool effect to EditText as it will fill in from the cents.

    
14.11.2017 / 13:16