How to make monetary mask on Edit Text Android

Asked

Viewed 1,551 times

2

Good morning gentlemen, I’m having trouble putting a monetary mask on an Edit Text, I checked several forums and tutorials but no method worked. My project is to basically make the customer put the value of the product in Edit Text, this is already working, however I would like to put a mask, could help me ?

public class Tecladonumerico extends AppCompatActivity {
    public Button botao1;
    public Button botao2;
    public Button botao3;
    public Button botao4;
    public Button botao5;
    public Button botao6;
    public Button botao7;
    public Button botao8;
    public Button botao9;
    public Button botao0;
    public Button botaoX;
    public Button botaoC;
    public Button botaoA;
    public EditText valor;

    Boolean bool = false;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {

        super.onCreate( savedInstanceState );
        setContentView( R.layout.layoutcores );
        DisplayMetrics dm = new DisplayMetrics();

        getWindowManager().getDefaultDisplay().getMetrics( dm );
        int width = dm.widthPixels;
        int height = dm.heightPixels;
        getWindow().setGravity( Gravity.TOP );
        getWindow().setLayout( (int) (width * .8), (int) (height * .8) );


//AQUI ESTÁ A VÁRIAVEL QUE CHAMA OS DADOS DO EDIT TEXT
        valor = (EditText) findViewById( R.id.calcula);

        botao1 = (Button) findViewById(R.id.button1);
        botao2 = (Button) findViewById(R.id.button2);
        botao3 = (Button) findViewById(R.id.button3);
        botao4 = (Button) findViewById(R.id.button4);
        botao5 = (Button) findViewById(R.id.button5);
        botao6 = (Button) findViewById(R.id.button6);
        botao7 = (Button) findViewById(R.id.button7);
        botao8 = (Button) findViewById(R.id.button8);
        botao9 = (Button) findViewById(R.id.button9);
        botao0 = (Button) findViewById(R.id.button0);
        botaoA= (Button) findViewById(R.id.buttona);
        botaoX = (Button) findViewById(R.id.buttonx);
        botaoC = (Button) findViewById(R.id.buttonc);


    }



    public void onBackPressed() {
        super.onBackPressed();

        Intent intent = new Intent();
        setResult(RESULT_CANCELED, intent);
        finish();
    }

    public void Botao1(View view){
        if (bool == false){

            String str = valor.getText().toString();
            valor.setText(str + "1");
        }
    }

    public void Botao2(View view){
        if (bool == false){
            String str = valor.getText().toString();
            valor.setText(str + "2");
        }
    }

    public void Botao3(View view){
        if (bool == false){
            String str = valor.getText().toString();
            valor.setText(str + "3");
        }
    }

    public void Botao4(View view){
        if (bool == false){
            String str = valor.getText().toString();
            valor.setText(str + "4");
        }
    }

    public void Botao5(View view){
        if (bool == false){
            String str = valor.getText().toString();
            valor.setText(str + "5");
        }
    }

    public void Botao6(View view){
        if (bool == false){
            String str = valor.getText().toString();
            valor.setText(str + "6");
        }
    }

    public void Botao7(View view){
        if (bool == false){
            String str = valor.getText().toString();
            valor.setText(str + "7");
        }
    }

    public void Botao8(View view){
        if (bool == false){
            String str = valor.getText().toString();
            valor.setText(str + "8");
        }
    }

    public void Botao9(View view){
        if (bool == false){
            String str = valor.getText().toString();
            valor.setText(str + "9");
        }
    }

    public void Botao0(View view){
        if (bool == false){
            String str = valor.getText().toString();
            valor.setText(str + "0");
        }
    }

    public void BotaoC(View view){
        if (bool == false){
            String str = valor.getText().toString();
            valor.setText("");
        }
    }

    public void BotaoA(View view){
        String str = valor.getText().toString();
        Intent intent = new Intent();
        intent.putExtra("KEY", str);
        this.setResult(RESULT_OK, intent);
        this.finish();
    }

    public void botaoX(View v){
        this.finish();
    }
} 
  • 1

    What would this value.setText(str + "1")... did not understand this. I have a mask here that leaves the format of the Edittext numbers according to the location of the person. example 1000 in Br is 1,000.00 in USA 1,000.00 in some European countries 1 000.00

  • this (str+"1") allows me to put the number "1" as many times as I want in the value field, for example: if I fill in once the value of str will be "1", then I will fill in again with the same value and it will become "11" and so on

1 answer

1


Create the following class:

public class MoneyTextWatcher implements TextWatcher {
    private final WeakReference<EditText> editTextWeakReference;
    private final Locale locale = Locale.getDefault();

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

    @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());
        String formatted = NumberFormat.getCurrencyInstance(locale).format(parsed);
        //Remove o símbolo da moeda e espaçamento pra evitar bug
        String replaceable = String.format("[%s\\s]", getCurrencySymbol());
        String cleanString = formatted.replaceAll(replaceable, "");

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

    private BigDecimal parseToBigDecimal(String value) {
        String replaceable = String.format("[%s,.\\s]", getCurrencySymbol());

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

        try {
            return new BigDecimal(cleanString).setScale(
                    2, BigDecimal.ROUND_FLOOR).divide(new BigDecimal(100), BigDecimal.ROUND_FLOOR);
        } catch (NumberFormatException e) {
            //ao apagar todos valores de uma só vez dava erro
            //Com a exception o valor retornado é 0.00
            return new BigDecimal(0);

        }
    }

    public static String formatPrice(String price) {
        //Ex - price = 2222
        //retorno = 2222.00
        DecimalFormat df = new DecimalFormat("0.00");
        return String.valueOf(df.format(Double.valueOf(price)));

    }

    public static String formatTextPrice(String price) {
        //Ex - price = 3333.30
        //retorna formato monetário em Br = 3.333,30
        //retorna formato monetário EUA: 3,333.30
        //retornar formato monetário de alguns países europeu: 3 333,30
        BigDecimal bD = new BigDecimal(formatPriceSave(formatPrice(price)));
        String newFormat = String.valueOf(NumberFormat.getCurrencyInstance(Locale.getDefault()).format(bD));
        String replaceable = String.format("[%s]", getCurrencySymbol());
        return newFormat.replaceAll(replaceable, "");

    }

    static String formatPriceSave(String price) {
        //Ex - price = $ 5555555
        //return = 55555.55 para salvar no banco de dados
        String replaceable = String.format("[%s,.\\s]", getCurrencySymbol());
        String cleanString = price.replaceAll(replaceable, "");
        StringBuilder stringBuilder = new StringBuilder(cleanString.replaceAll(" ", ""));

        return String.valueOf(stringBuilder.insert(cleanString.length() - 2, '.'));

    }

    public static String getCurrencySymbol() {
        return NumberFormat.getCurrencyInstance(Locale.getDefault()).getCurrency().getSymbol();

    }
}

Within the onCreate of your Activity and dpois to initialize editText, add:

valor.addTextChangedListener(new MoneyTextWatcher(valor));

Option: In your Buttonthe that sends this Edittext String remember that you will be sending a value depending on the user’s device configuration. Value "1000", if in Pt-Br will be 1,000.00 in US 1,000.00 in some countries of Europe 1,000.00, if you want to send as default value "1000.00" to a database leave in Botãoa:

String str = formatPriceSave(valor.getText().toString());

if you need to recover this value later and turn it into monetary again you can recover it normal and use the formatTextPrice method that will transform 1000.00 to the monetary standard that the device is configured.

  • 1

    I used this mask for a long time, I never had problems. I saw an example of it a while ago, and I changed it to what I needed. And tested here for your example and worked well.

Browser other questions tagged

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