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

问题描述 投票:1回答:2

我有一个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) {
}

}

java android android-edittext
2个回答
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
投票

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

public static String formatCurrencyDigit(long amount) {
    return String.format("%,d%s %s", amount, "", "");
}
© www.soinside.com 2019 - 2024. All rights reserved.