I would like to display the input of the EditText fields with two decimals at all times. So when the user enters 5 it will show 5.00 or when the user enters 7.5 it will show 7.50.
Besides that I would like to also show zero when the field is empty instead of nothing.
What I've got already is the inputtype set to:
android:inputType="number|numberDecimal"/>
Should I work with inputfilters here?
Sorry I still quite new to android / java...
Thanks for your help!
Edit 2011-07-09 23.35 - Solved part 1 of 2: The "" to 0.00.
With the answer of nickfox I was able to solve half of my question.
et.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
public void onTextChanged(CharSequence s, int start, int before, int count) {
if(s.toString().matches(""))
{
et.setText("0.00");
Selection.setSelection(et.getText(), 0, 4);
}
}
});
I'm still working on a solution for the other half of my question. If I found the solution I will post it here too.
Edit 2011-07-09 23.35 - Solved part 2 of 2: Change user input to a number with two decimals.
OnFocusChangeListener FocusChanged = new OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(!hasFocus){
String userInput = et.getText().toString();
int dotPos = -1;
for (int i = 0; i < userInput.length(); i++) {
char c = userInput.charAt(i);
if (c == '.') {
dotPos = i;
}
}
if (dotPos == -1){
et.setText(userInput + ".00");
} else {
if ( userInput.length() - dotPos == 1 ) {
et.setText(userInput + "00");
} else if ( userInput.length() - dotPos == 2 ) {
et.setText(userInput + "0");
}
}
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…