我想要实现的是EditText
具有以下行为:
首先,文字显示:
0.00(en_GB local)或0,00(fr_FR local)
当用户输入数字4时,Edittext显示:
0.04(en_GB)或0,04(fr_FR)
当用户输入另一个6:
时0.46(en_GB)或0,46(fr_FR)
等
当本地设置为en_GB时,我的代码工作得很好,但是当局部更改为fr_FR时,我得到一个无限循环。
以下是代码:
EditText布局:
<EditText
android:id="@+id/amount_ET"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="numberDecimal"
android:maxLength="8" />
和java代码:
amountEditText = (EditText) findViewById(R.id.amount_ET);
amountEditText.setText(mValueToString());
// ensure the cursor is always in the beginning of the text.
amountEditText.setOnFocusChangeListener(new OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (v.hasFocus()) {
int len = amountEditText.getEditableText().toString().trim().length();
if (len > 1) {
amountEditText.setSelection(0);
amountEditText.setCursorVisible(false);
}
}
}
});
// add listener in order to intercept input on the EditText
amountEditText.addTextChangedListener(new TextWatcher() {
@Override
public void afterTextChanged(Editable s) {
// we only update if the value is not what we expect to avoid infinite loop
if (!s.toString().isEmpty() && !s.toString().equals(mValueToString())) {
// the cursor is always at the first position, so new char are in the beginning of the editable
updateAmountTextView(s, s.charAt(0));
}
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
});
}
/**
* Update the new value with the given numeral and update the given Editable with the new value.
*
* @param s
* if not null, will be updated with the formatted value.
* @param c
* the char representing the number to insert.
*/
protected void updateAmountTextView(Editable s, char c) {
Integer i = Integer.valueOf(c - 48);
mValue = mValue * 10 + i;
if (s != null) {
s.clear();
s.append(mValueToString()); // when using fr_FR local, the coma is not appended leading to a false value in the editable.
}
amountEditText.setSelection(0);
}
/**
* return the String formatted value.
*/
protected String mValueToString() {
Double d = Double.valueOf(mValue) / 100;
NumberFormat formatter = new DecimalFormat("#0.00");
return formatter.format(d);
}
在java代码的注释中已经解释过,错误在方法updateAmountTextView()
中,Editable
拒绝接受昏迷。
将inputType
的{{1}}更改为值EditText
时,不会发生此错误,除非我希望软键盘仅接受数字。
我想我应该在text
对象上做一些事情,然后再附加值,但我在文档中找不到任何相关内容。
答案 0 :(得分:1)
正如https://stackoverflow.com/users/427291/devisnik的评论中所指出的,在android:digits="0123456789.,"
布局中添加行Edittext
解决了这个问题。