简体   繁体   English

带有货币格式的EditText

[英]EditText with Currency format

I have a EditText in which I want to display currency: 我有一个EditText,我想在其中显示货币:

    input.setInputType(InputType.TYPE_CLASS_NUMBER);
    input.addTextChangedListener(new CurrencyTextWatcher());

with: 有:

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

on my EditText. 在我的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. 但是:如果我不通过input.setInputType(InputType.TYPE_CLASS_NUMBER)设置inputType,则格式化工作完美。 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? 如何使用数字键盘并在EditText中查看正确的货币格式? Thanks. 谢谢。

It is better to use InputFilter interface. 最好使用InputFilter接口。 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;
}
}

Valid: 0.00, 0.0, 10.00, 111.1 有效期:0.00,0.0,10.00,111.1
Invalid: 0, 0.000, 111, 10, 010.00, 01.0 无效:0,0.000,111,10,010.00,01.0

How to use: 如何使用:

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

Try add this property in you xml declaration for you edit text: 尝试在xml声明中添加此属性,以便编辑文本:

android:inputType="numberDecimal" or number or signed number android:inputType="numberDecimal"或数字或签名号码

See more info about android:inputType here . 在这里查看更多关于android:inputType 信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM