使用Android中的EditText格式化货币字符串

时间:2014-10-23 16:57:05

标签: java android string formatting android-edittext

我试图在Android中格式化EditText的输入值,我想用货币值格式化输入,我'我尝试了以下方法:

EditText minimo = (EditText) view.findViewById(R.id.minimo);

Locale locale = new Locale("en", "UK");
NumberFormat fmt = NumberFormat.getCurrencyInstance(locale);

 Locale locale = new Locale("en", "UK");
    NumberFormat fmt = NumberFormat.getCurrencyInstance(locale);

    minimo.setText("", TextView.BufferType.valueOf(String.valueOf(fmt.format(TextView.BufferType.EDITABLE))));

日志:

java.lang.IllegalArgumentException: Bad class: class android.widget.TextView$BufferType

1 个答案:

答案 0 :(得分:11)

试试这个:

TextChangedListner设为:

minimo.addTextChangedListener(new NumberTextWatcher(minimo));

将自定义TextWatcher创建为:

class NumberTextWatcher implements TextWatcher {

    private DecimalFormat df;
    private DecimalFormat dfnd;
    private boolean hasFractionalPart;

    private EditText et;

    public NumberTextWatcher(EditText et)
    {
        df = new DecimalFormat("#,###.##");
        df.setDecimalSeparatorAlwaysShown(true);
        dfnd = new DecimalFormat("#,###");
        this.et = et;
        hasFractionalPart = false;
    }

    @SuppressWarnings("unused")
    private static final String TAG = "NumberTextWatcher";

    public void afterTextChanged(Editable s)
    {
        et.removeTextChangedListener(this);

        try {
            int inilen, endlen;
            inilen = et.getText().length();

            String v = s.toString().replace(String.valueOf(df.getDecimalFormatSymbols().getGroupingSeparator()), "");
            Number n = df.parse(v);
            int cp = et.getSelectionStart();
            if (hasFractionalPart) {
                et.setText(df.format(n));
            } else {
                et.setText(dfnd.format(n));
            }
            endlen = et.getText().length();
            int sel = (cp + (endlen - inilen));
            if (sel > 0 && sel <= et.getText().length()) {
                et.setSelection(sel);
            } else {
                // place cursor at the end?
                et.setSelection(et.getText().length() - 1);
            }
        } catch (NumberFormatException nfe) {
            // do nothing?
        } catch (ParseException e) {
            // do nothing?
        }

        et.addTextChangedListener(this);
    }

    public void beforeTextChanged(CharSequence s, int start, int count, int after)
    {
    }

    public void onTextChanged(CharSequence s, int start, int before, int count)
    {
        if (s.toString().contains(String.valueOf(df.getDecimalFormatSymbols().getDecimalSeparator())))
        {
            hasFractionalPart = true;
        } else {
            hasFractionalPart = false;
        }
    }
}