Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
561 views
in Technique[技术] by (71.8m points)

android - EditText with Currency format

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

    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. 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...