Android Money Input with fixed decimal

How do you create an edittext entry that formats input in money format only? When the user enters 5, I want the input to look like "$0.05" and when they then enter 3, the input should now look like "$0.53" and finally they enter 6 and the input should look like "$5.36".


Solution 1:

ninjasense's complete solution basically works, but it has some issues:

  1. Every time the data of the field is altered in the "onTextChanged" handler, cursor position resets to index 0 on the field, which is a bit annoying to happen when typing in monetary values.
  2. It uses floats for formatting monetary values, which can backfire.

For the first problem I don't have solution yet, for the second one code like this works:

    @Override
    public void onTextChanged(CharSequence s, int start,
            int before, int count) {
        if(!s.toString().matches("^\\$(\\d{1,3}(\\,\\d{3})*|(\\d+))(\\.\\d{2})?$"))
        {
            String userInput= ""+s.toString().replaceAll("[^\\d]", "");
            StringBuilder cashAmountBuilder = new StringBuilder(userInput);

            while (cashAmountBuilder.length() > 3 && cashAmountBuilder.charAt(0) == '0') {
                cashAmountBuilder.deleteCharAt(0);
            }
            while (cashAmountBuilder.length() < 3) {
                cashAmountBuilder.insert(0, '0');
            }
            cashAmountBuilder.insert(cashAmountBuilder.length()-2, '.');
            cashAmountBuilder.insert(0, '$');

            cashAmountEdit.setText(cashAmountBuilder.toString());
        }

    }

Solution 2:

Building off Zds.

For keeping the cursor positioned at the end of the field use this.

cashAmountEdit.setTextKeepState(cashAmountBuilder.toString());
Selection.setSelection(cashAmountEdit.getText(), cashAmountBuilder.toString().length());

Solution 3:

You can use a TextWatcher to do that kind of thing.

Extend TextWatcher: http://d.android.com/reference/android/text/TextWatcher.html

public class MyTextWatcher implements TextWatcher {

    public void afterTextChanged(Editable arg0) { 

    }

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

    }

    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

}

Then add it to your editText with

myEditText.addTextChangedListener(new MyTextWatcher());