EditText with Currency format

后端 未结 2 937
死守一世寂寞
死守一世寂寞 2020-12-11 02:20

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

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


        
相关标签:
2条回答
  • 2020-12-11 02:38

    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()});
    
    0 讨论(0)
  • 2020-12-11 02:51

    Try add this property in you xml declaration for you edit text:

    android:inputType="numberDecimal" or number or signed number

    See more info about android:inputType here.

    0 讨论(0)
提交回复
热议问题