我需要格式化输入到 EditText
中的货币值,所以我使用了 TextWatcher
但现在我在软键盘中遇到退格键问题。
通常,如果您按住键盘上的backspace键,它会不断删除EditText
中的字符,直到出现什么都没有了。添加 TextWatcher
后,您需要手动按下退格按钮多次才能完全摆脱所有字符作为holding它不再有效。
我该如何解决?
public class NumberTextWatcher implements TextWatcher {
private final EditText et;
public NumberTextWatcher(EditText et) {
this.et = et;
}
@Override
public void afterTextChanged(Editable s) {
et.removeTextChangedListener(this);
try {
String originalString = s.toString();
long longval;
if (originalString.contains(",")) {
originalString = originalString.replaceAll(",", "");
}
longval = Long.parseLong(originalString);
DecimalFormat formatter = (DecimalFormat) NumberFormat.getInstance(Locale.US);
formatter.applyPattern("#,###,###,###");
String formattedString = formatter.format(longval);
//setting text after format to EditText
et.setText(formattedString);
et.setSelection(et.getText().length());
} catch (NumberFormatException nfe) {
nfe.printStackTrace();
}
et.addTextChangedListener(this);
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
}
最佳答案
根据 afterTextChanged(Editeable s)
文档,此 EditText
上发生的任何更改都将从此回调中得到通知,并且很明显,此回调锁定退格回调,以便根据需要重新格式化文本 "#, ###,###,###"
适当的修复:您需要继续处理您的代码 only and only if the input wasn't the backspace key ,即:
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
if (after < count) {
isBackspaceClicked = true;
} else {
isBackspaceClicked = false;
}
}
@Override
public void afterTextChanged(Editable s) {
if (!isBackspaceClicked) {
// Your current code
}
}
关于android - 使用 TextWatcher 时退格键无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57419773/