android - 如何在 EditText 中用逗号分隔数字
问题描述
我有一个 EditText ,它的 inputType 为number。当用户输入时,我想用逗号分隔数字。这是一个小例子:
123 将表示为 123
1234 将表示为 1,234
12345 将表示为 12,345
...等等。
我尝试使用 TextWatcher 添加逗号,如下所示:
EditText edittext = findViewById(R.id.cashGiven);
edittext.addTextChangedListener(new TextWatcher(){
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void afterTextChanged(Editable editable) {
editText.setText(separateWithComma(editText.getText().toString().trim()));
}
});
在此处粘贴该separateWithComma()
方法会使这个问题变得格外冗长,但它确实有效:我在 Eclipse 上对其进行了测试。我认为 addTextChangedListener 不能以这种方式工作,因为当我这样做时,我的应用程序会冻结(然后在很久以后崩溃)。
有没有更好的方法来实现这一目标?感谢期待积极的回应。
解决方案
试试这个代码:
et.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
@Override
public void afterTextChanged(Editable s) {
et.removeTextChangedListener(this);
try {
String givenstring = s.toString();
Long longval;
if (givenstring.contains(",")) {
givenstring = givenstring.replaceAll(",", "");
}
longval = Long.parseLong(givenstring);
DecimalFormat formatter = new DecimalFormat("#,###,###");
String formattedString = formatter.format(longval);
et.setText(formattedString);
et.setSelection(et.getText().length());
// to place the cursor at the end of text
} catch (NumberFormatException nfe) {
nfe.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
et.addTextChangedListener(this);
}
});
推荐阅读
- tensorflow - 属性错误:- TensorFlow 没有属性“会话”。我应该如何解决这个错误?我正在使用 Mac Catalina 操作系统
- javascript - 使用 google Drive API 与特定用户共享上传的文件
- python - 有没有办法在 OpenCV Python 中访问所需边缘的坐标?
- python - 如何在 PyTorch 中正确实现数值数据的 1D CNN?
- javascript - 获取一些选定的选项 javascript
- yii2 - 如何在 yii2 活动形式的占位符内使用 Yii:t()
- python - 通过 Selenium 选择子 css 元素不起作用
- c++ - 立即传递其成员时的右值范围
- angular - 角度方法的返回类型需要解释
- c++ - 如何始终使用 minAreaRect,c++ 将图像旋转到 180 度