【发布时间】:2014-11-19 21:12:04
【问题描述】:
通过 SO,我将以下 EditText addTextChangedListener 事件处理程序放在一起,它工作正常,除了我需要一些改进。当我输入时,它会从右到左填充数字。我宁愿它从左到右填充。现在,如果我输入 50,它的格式为 $0.50,当我输入 50 时,我希望它的格式为 $50.00
以下是 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);
}
}
});
【问题讨论】:
-
这是我从另一个 SO 问题中得到的结果
-
@skywall 这就是他们添加之前删除的小数的方式。由于并非所有货币都有 2 个小数位,因此无法在全球范围内使用的肮脏解决方案。