问题描述
我有一个EditText,其inputType为 number .用户输入时,我想用逗号分隔数字.这是一个小例子:
I have an EditText that has an inputType of number. While the user is typing, I want to comma-separate the numbers. Here's a little illustration:
1234将表示为1,234
1234 would be represented as 1,234
12345将表示为12,345
12345 would be represented as 12,345
...等等.
我尝试使用TextWatcher添加逗号,如下所示:
I tried adding a comma with TextWatcher as shown below:
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无法以这种方式工作,因为执行此操作时我的应用程序冻结(然后崩溃).
Pasting the separateWithComma()
method here would make this question extra lengthy but then, it works: I tested it on Eclipse. I think the addTextChangedListener does not work this way because my app freezes (and then crashes much later) when I do this.
是否有更好的方法来实现这一目标?谢谢您的积极回应.
Is there a better way to achieve this? Thanks in anticipation for a positive response.
推荐答案
尝试使用String.format
而不是现在的版本.
替换此:
Try to use String.format
instead of what you have now.
Replace this:
editText.setText(separateWithComma(editText.getText().toString().trim()));
与此:
editText.setText(String.format("%,d", your number));
另一件事-您的应用程序可能会崩溃,因为每次在afterTextChanged
内部调用setText()
时,都会调用另一个afterTextChanged
,并且基本上会创建一个无限循环.如果这是您的问题,您可以找到一个很好的解决方案.
Another thing - your app may be getting this crash because every time that you are calling setText()
inside afterTextChanged
, another afterTextChanged
is called and basically will create an infinite loop. If that is your problem you can find a good solution in here.
这篇关于如何在EditText中用逗号分隔数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!