通过SO我编写了以下EditText addTextChangedListener事件处理程序,它工作得很好,除了我需要的一点改进。当我输入时,它从右到左填充数字。我希望它从左到右填充。现在如果我输入50,它会格式化为$0.50,而我想要它格式化为$50.00。
以下是xml声明和Java代码,请有人指点我需要更改什么以获得所需的结果。
XML声明:
以下是xml声明和Java代码,请有人指点我需要更改什么以获得所需的结果。
XML声明:
<EditText
android:id="@+id/valueEditText"
android:layout_row="1"
android:hint="@string/hint_value_to_add"
android:imeOptions="actionNext"
android:inputType="numberDecimal"
style="@style/EnrollEditViewStyle" />
<requestFocus />
Java 代码
inputValue = (EditText) findViewById(R.id.valueEditText);
inputValue.addTextChangedListener(new TextWatcher() {
private String current = "";
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
@Override
public void afterTextChanged(Editable s) {
if (!s.toString().equals(current)) {
inputValue.removeTextChangedListener(this);
String replaceable = String.format("[%s,.\\s]", NumberFormat.getCurrencyInstance().getCurrency().getSymbol());
String cleanString = s.toString().replaceAll(replaceable, "");
double parsed;
try {
parsed = Double.parseDouble(cleanString);
} catch (NumberFormatException e) {
parsed = 0.00;
}
String formatted = NumberFormat.getCurrencyInstance().format((parsed/100));
current = formatted;
inputValue.setText(formatted);
inputValue.setSelection(formatted.length());
inputValue.addTextChangedListener(this);
}
}
});