2

In my Android app I've got an EditText in which the user can enter an amount. When the EditText loses focus I format the entered amount to a currency Locale using NumberFormat, and when the user clicks the edittext, it takes the original string again and enters that (code here).

This works fine, but it doesn't really look pretty while the user enters the amount. Ideally I would like the EditText to also display the following (in order of importance):

  1. the Currency symbol on the left of the amount.
  2. Localised thousand separators.
  3. Decimal mark only if it is entered by the user.

The first problem I run into however, is that when I use a TextWatcher and implement something like the snippet below, I get a (how well suited to this website) StackOverflowException, because it then watches its own change.

@Override
public void afterTextChanged(Editable s) {
    amount_field.setText("€" + s.toString());
}

So my question: how do you format an EditText in realtime? All tips are welcome!

kramer65
  • 50,427
  • 120
  • 308
  • 488
  • try this for the textwatcher http://stackoverflow.com/questions/11134144/android-edittext-onchange-listener – Pedro Bernardo Dec 06 '13 at 09:00
  • You can always remove the textwatcher, set the text and add the textwatcher. Not really a clean solution but it should work. – Tobrun Dec 06 '13 at 09:02

1 Answers1

0

Try using on OnFocusChangeListener in following way:

<EDIT-TEXT>.setOnFocusChangeListener(new OnFocusChangeListener() {

    @Override
    public void onFocusChange(View arg0, boolean arg1) {
        if(!arg1){//it means focus is shifted
            amount_field.setText("€" + s.toString());
        }

    }
});

Try doing something like this:

String lastText="";
@Override
public void afterTextChanged(Editable s) {
    if(!lastText.equals(s.toString())){
       String str=s.toString();
       str = str.replaceAll("\\D+", "");
       Locale dutch = new Locale("nl", "NL");
       NumberFormat numberFormatDutch = NumberFormat.getCurrencyInstance(dutch);
       String formattedAmount = numberFormatDutch.format(new BigDecimal(str));
       formattedAmount ="€" + formattedAmount;
       lastText=formattedAmount;
       amount_test.setText(formattedAmount);
    }
}
vipul mittal
  • 17,343
  • 3
  • 41
  • 44
  • Thanks for the tip, but doesn't `if(!arg1) {` mean that the EditText just lost focus? That is not the problem unfortunately. I currently already format the field while after it lost focus (see my current code: http://pastebin.com/VG8V5eaV) I want the EditText to change *during* the editing by the user. – kramer65 Dec 06 '13 at 09:17