[英]Android EditText AddTextChangeListener Currency Format
[英]Android format value currency when user type number on EditText
我正在尝试格式化在EditText
输入的值,这必须立即发生,即,一旦用户在EditText
输入值,应用程序就必须格式化该值并将其再次设置为EditText
。 我的代码不正确,我找不到按时格式化数字的任何方法
transfer_amount.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void afterTextChanged(Editable charSequence) {
if (charSequence.toString().length() == 1 && charSequence.toString().equals("0")) {
transfer_amount.setText("");
} else if (charSequence.toString().length() > 0 && (int) charSequence.toString().charAt(0) >= 48 && (int) charSequence.toString().charAt(0) <= 57) {
Locale swedish = new Locale("sv", "SE");
NumberFormat swedishFormat = NumberFormat.getCurrencyInstance(swedish);
transfer_amount.setText(swedishFormat.format(Long.parseLong((charSequence.toString()))));
}
}
});
public void onTextChanged(CharSequence s, int start, int before, int count) {
long enteredNumber = Long.parseLong(s.toString().replace(",", ""));
transfer_amount.removeTextChangedListener(this);
DecimalFormat formatter = new DecimalFormat("#,###,###");
String yourFormattedString = formatter.format(enteredNumber);
Log.e("yourFormattedString ", yourFormattedString);
transfer_amount.setText(yourFormattedString);
transfer_amount.addTextChangedListener(this);
}
此代码将一直工作到格式编号,当格式化了我的EditText时,我不知道是什么问题,
我的日志:
E/yourFormattedString: 1
E/yourFormattedString: 11
E/yourFormattedString: 111
E/yourFormattedString: 1,111
E/yourFormattedString: 1
对于文本更改运行时,您需要注意原始字符串和修改后的字符串。
tt = new TextWatcher() {
public void afterTextChanged(Editable s) {
if(s.length()!=0) {
long enteredNumber = Long.parseLong(s.toString().replace(",", ""));
nameEdit.removeTextChangedListener(this);
DecimalFormat formatter = new DecimalFormat("#,###,###");
String yourFormattedString = formatter.format(enteredNumber);
Log.e("yourFormattedString ", yourFormattedString);
nameEdit.setText(yourFormattedString);
nameEdit.addTextChangedListener(this);
nameEdit.setSelection(yourFormattedString.length());
}
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
};
nameEdit.addTextChangedListener(tt);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.