如何在EditText中添加数字分隔符 [英] How to add number separators in EditText

查看:185
本文介绍了如何在EditText中添加数字分隔符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have an Edittext and want to set the EditText so that when the user is inputting the number to be converted, a thousand separator (,) should be added automaticaaly in realtime to the number .but i want do this in "onTextChanged" method not in the "afterTextChanged" method. How can I?

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) {
}

}

推荐答案

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

I use a TextWatcher to trig on every change in EditText, and use this code to separate currency sections and then set to EditText after every character changes:

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

这篇关于如何在EditText中添加数字分隔符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆