Friday, June 4, 2010

[android-developers] How to custom format text in EditText

I'm just starting to drink from the fire hose that is android. For my
first project I would like to have an EditText field for numeric input
that will automatically reformat the input as the user types to
something like:

#,##0.00

as the user types in the value. I can't seen to find the right place
to add the code, I thought something like:

EditText edittext = (EditText)findViewById(R.id.num_input);
edittext.setOnKeyListener(new OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
DecimalFormat twoDecimalPlaces = new DecimalFormat("#,##0.00");
String valStr = ((EditText)v).getText().toString();
double val = Double.parseDouble(cleanNumber(valStr));
((EditText)v).setText(twoDecimalPlaces.format(val));
return false;
}
});

the cleanNumber method strips out the commas from the string so it can
be parsed.

This does not work however. For one it is called before the key
stroke is added to the text. Any suggestions on the best way to do
this?

Jim

--
You received this message because you are subscribed to the Google
Groups "Android Developers" group.
To post to this group, send email to android-developers@googlegroups.com
To unsubscribe from this group, send email to
android-developers+unsubscribe@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/android-developers?hl=en

No comments:

Post a Comment