EditText上外币格式外币、格式、EditText

2023-09-13 01:54:15 作者:櫻花落″舞一世傾城

我有,我想显示货币的EditText:

I have a EditText in which I want to display currency:

    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;
    }
}

我希望用户看到的数只键盘,这就是为什么我称之为

I want to user to see a number-only keyboard, that is why I call

input.setInputType(InputType.TYPE_CLASS_NUMBER);

在我的EditText。然而,这是行不通的。我看到的数字是键入不带任何格式。但是:如果我不通过input.setInputType(InputType.TYPE_CLASS_NUMBER)不将inputType,格式完美的作品。但用户必须使用普通键盘,这是不是很好。我如何使用数字键盘,也看到我的EditText正确的货币格式?谢谢你。

on my EditText. However, it does not work. I see the numbers as typed in without any formatting. BUT: If I DO NOT set the inputType via input.setInputType(InputType.TYPE_CLASS_NUMBER), the formatting works perfectly. But the user must use the regular keyboard, which is not nice. How can I use the number keyboard and also see the correct currency formatting in my EditText? Thanks.

推荐答案

这是更好地使用输入过滤器接口。很容易通过使用正则表达式来处理任何类型的输入。我的货币输入格式的解决方案:

It is better to use InputFilter interface. Much easier to handle any kind of inputs by using regex. My solution for currency input format:

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 使用方法:

Valid: 0.00, 0.0, 10.00, 111.1 Invalid: 0, 0.000, 111, 10, 010.00, 01.0 How to use:

editText.setFilters(new InputFilter[] {new CurrencyFormatInputFilter()});