我有一个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. 我尝试
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.