当前位置: 代码迷 >> java >> 如何在EditText中添加数字分隔符
  详细解决方案

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

热度:93   发布时间:2023-08-02 10:22:19.0

我有一个Edittext,并希望设置EditText,以便当用户输入要转换的数字时,应实时自动向该数字中添加一千个分隔符(,),但是我想在“ onTextChanged”方法中做到这一点在“ afterTextChanged”方法中。 我怎样才能?

public class NumberTextWatcherForThousand implements TextWatcher {

EditText editText;


public NumberTextWatcherForThousand(EditText editText) {
    this.editText = editText;


}

@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {

}

@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {

}

@Override
public void afterTextChanged(Editable view) {
String s = null;
try {
    // The comma in the format specifier does the trick
    s = String.format("%,d", Long.parseLong(view.toString()));
    edittext.settext(s);
} catch (NumberFormatException e) {
}

}

试试这个代码:

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

            }
        });

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

public static String formatCurrencyDigit(long amount) {
    return String.format("%,d%s %s", amount, "", "");
}
  相关解决方案