首页 > 解决方案 > 如何在 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 不能以这种方式工作,因为当我这样做时,我的应用程序会冻结(然后在很久以后崩溃)。

有没有更好的方法来实现这一目标?感谢期待积极的回应。

标签: androidandroid-edittextnumber-formatting

解决方案


试试这个代码:

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);

            }
        });

看到这个帖子


推荐阅读