android– 如何用逗号分隔EditText中的数字

android– 如何用逗号分隔EditText中的数字,第1张

概述我有一个EditText,其inputType为number.当用户输入时,我想用逗号分隔数字.这是一个小插图:123wouldberepresentedas1231234wouldberepresentedas1,23412345wouldberepresentedas12,345…andsoon.我尝试使用TextWatcher添加逗号,如下所示:EditTextedi

我有一个EditText,其inputType为number.当用户输入时,我想用逗号分隔数字.这是一个小插图:

123 would be represented as 123

1234 would be represented as 1,234

12345 would be represented as 12,345

…and so on.

我尝试使用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不能以这种方式工作,因为当我这样做时,我的应用程序会冻结(然后会崩溃很久).

有没有更好的方法来实现这一目标?感谢您对积极的回应.

解决方法:

尝试使用String.format而不是现在的.
 替换这个:

editText.setText(separateWithComma(editText.getText().toString().trim()));

有了这个:

editText.setText(String.format("%,d", your number));

另一件事 – 您的应用程序可能会遇到此崩溃,因为每次在afterTextChanged中调用setText()时,都会调用另一个afterTextChanged,并且基本上会创建一个无限循环.如果这是你的问题,你可以找到一个很好的解决方案in here.

总结

以上是内存溢出为你收集整理的android – 如何用逗号分隔EditText中的数字全部内容,希望文章能够帮你解决android – 如何用逗号分隔EditText中的数字所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://www.outofmemory.cn/web/1112502.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-29
下一篇 2022-05-29

发表评论

登录后才能评论

评论列表(0条)

保存