【问题标题】:How to add number separators in EditText如何在 EditText 中添加数字分隔符
【发布时间】:2019-07-08 05:34:13
【问题描述】:

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


【解决方案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);

            }
        });

【讨论】:

  • 是的,你可以。 :)
  • 我是 android 的初学者。 ;)
  • masoud.mokhtari69@gmail.com
  • 如果我的答案是正确的,请选择我的答案是正确的。谢谢
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-06
    • 1970-01-01
    • 1970-01-01
    • 2019-07-10
    • 1970-01-01
    • 1970-01-01
    • 2013-10-09
    • 2015-12-11
    相关资源
    最近更新 更多