如何在EditText中添加数字分隔符

时间:2019-02-14 08:39:35

标签: java android android-edittext

我有一个Edittext,并希望设置EditText,以便当用户输入要转换的数字时,应实时自动将一千个分隔符(,)自动添加到数字中。但是我想在“ onTextChanged”中执行此操作”方法不在“ afterTextChanged”方法中。我该怎么办?

rebase -i <after-this-commit>

}

2 个答案:

答案 0 :(得分:1)

尝试以下代码:

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

            }
        });

答案 1 :(得分:1)

我使用TextWatcher来触发EditText中的每次更改,并使用此代码来分隔货币部分,然后在每次字符更改后将其设置为EditText:

public static String formatCurrencyDigit(long amount) {
    return String.format("%,d%s %s", amount, "", "");
}