Reputation: 11328
what's the best way to mask a EditText on Android?
I Would like my EditText to behave like this decimal number input here.
Is there a easy way to do this?
Upvotes: 8
Views: 5395
Reputation: 8530
I built a decimal mask for an edit text that will auto change the edit text to the number of decimal places you want. Bascially, you listen for text changes and loss of focus.
private void formatNumber() {
sNumberToFormat = etNumberToFormat.getText().toString();
sDecimalMask = etDecimalMask.getText().toString();
boolean periodMask = false;
String delimiter = getDelimiter();
String[] decimalMask = getsDecimalMask();
if (decimalMask.length == 1) {
return;
} else {
if (delimiter.equalsIgnoreCase(",")) {
//decimal format only currently works with dot delimiters.
sDecimalMask = sDecimalMask.replace(",", ".");
}
DecimalFormat df = new DecimalFormat(sDecimalMask);
df.setRoundingMode(RoundingMode.UP);
sNumberToFormat = df.format(Float.valueOf(sNumberToFormat.replace(",", ".")));
//if (maxNumber > Float.valueOf(sNumberToFormat)) {
if (delimiter.equalsIgnoreCase(",")) {
sNumberToFormat = sNumberToFormat.replace(".", ",");
}
etNumberToFormat.setText(sNumberToFormat);
}
}
The complete demo is here.
Upvotes: 0
Reputation: 20764
You have to programmatically set an InputFilter on your EditText
by setFilters.
From the documentation:
InputFilters can be attached to Editables to constrain the changes that can be made to them.
You can even change the users input, for example by adding a decimal point which is what you want if I get you correctly.
Upvotes: 2