我有一个EditText,我想显示货币:
input.setInputType(InputType.TYPE_CLASS_NUMBER); input.addTextChangedListener(new CurrencyTextWatcher());
有:
public class CurrencyTextWatcher implements TextWatcher { boolean mEditing; public CurrencyTextWatcher() { mEditing = false; } public synchronized void afterTextChanged(Editable s) { if(!mEditing) { mEditing = true; String digits = s.toString().replaceAll("\\D",""); NumberFormat nf = NumberFormat.getCurrencyInstance(); try{ String formatted = nf.format(Double.parseDouble(digits)/100); s.replace(0,s.length(),formatted); } catch (NumberFormatException nfe) { s.clear(); } mEditing = false; } }
input.setInputType(InputType.TYPE_CLASS_NUMBER);
在我的EditText上但是,它不起作用我看到没有格式化输入的数字.但是:如果我没有通过input.setInputType(InputType.TYPE_CLASS_NUMBER)设置inputType,则格式化将完美地工作.但用户必须使用普通键盘,这不是很好.如何使用数字键盘,并在我的EditText中看到正确的货币格式?谢谢.
解决方法
最好使用InputFilter接口.使用正则表达式更容易处理任何类型的输入.我的货币输入格式解决方案
public class CurrencyFormatInputFilter implements InputFilter { Pattern mPattern = Pattern.compile("(0|[1-9]+[0-9]*)?(\\.[0-9]{0,2})?"); @Override public CharSequence filter( CharSequence source,int start,int end,Spanned dest,int dstart,int dend) { String result = dest.subSequence(0,dstart) + source.toString() + dest.subSequence(dend,dest.length()); Matcher matcher = mPattern.matcher(result); if (!matcher.matches()) return dest.subSequence(dstart,dend); return null; } }
有效:0.00,0.0,10.00,111.1
无效:0,0.000,111,10,010.00,01.0
如何使用:
editText.setFilters(new InputFilter[] {new CurrencyFormatInputFilter()});