我正在尝试格式化在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
答案 0 :(得分:0)
对于文本更改运行时,您需要注意原始字符串和修改后的字符串。
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);