У меня есть editText, начальное значение - 0.00 $. Когда вы нажмете 1, он изменится на 0,01 доллара. Нажмите 4, он будет равен 0,14 доллара. Нажмите 8, $1,48. Нажмите backspace, $0.14 и т.д.
Это работает, проблема в том, что если кто-то вручную позиционирует курсор, в форматировании возникают проблемы. Если они должны были удалить десятичное число, оно не вернется. Если они помещают курсор перед десятичной точкой и тип 2, он будет отображать $02.00 вместо $2.00. Если они попытаются удалить $, то вместо этого они удалят цифру.
Вот код, который я использую, я был бы признателен за любые предложения.
mEditPrice.setRawInputType(Configuration.KEYBOARD_12KEY);
public void priceClick(View view) {
mEditPrice.addTextChangedListener(new TextWatcher(){
DecimalFormat dec = new DecimalFormat("0.00");
@Override
public void afterTextChanged(Editable arg0) {
}
@Override
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
@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]", "");
if (userInput.length() > 0) {
Float in=Float.parseFloat(userInput);
float percen = in/100;
mEditPrice.setText("$"+dec.format(percen));
mEditPrice.setSelection(mEditPrice.getText().length());
}
}
}
});