功能如标题,代码如下: ( 本代码 可直接用到你的项目中, 只需要将 EditText transactionMoney替换成你的即可 ) String abc = "" ; EditText transactionMoney ; //就是随便一个输入框,表示金额 //下面就是给editText加一个文字监听
transactionMoney .addTextChangedListener(new TextWatcher() { @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 s) { if (!s.toString().equals(abc )) { transactionMoney .removeTextChangedListener(this); String replaceable = String.format ("[%s, \\ s.]" , NumberFormat .getCurrencyInstance (Locale.CHINA ).getCurrency().getSymbol(Locale.CHINA )); String cleanString = s.toString().replaceAll(replaceable, "" ); if (cleanString.equals("" ) || new BigDecimal(cleanString).toString().equals("0" )) { transactionMoney .setText(null); } else { double parsed = Double.parseDouble (cleanString); String formatted = NumberFormat .getCurrencyInstance (Locale.CHINA ).format((parsed / 100 )); abc = formatted; transactionMoney .setText(formatted); transactionMoney .setSelection(formatted.length()); } transactionMoney .addTextChangedListener(this); } } });
希望对您有所帮助!