2

i'm working on an android application with an EditText box. In this box i want the user to enter currency.

I have already restricted the keyboard to numbers and decimals using the handy android:inputType="numberDecimal" but i would like to be able to stop the user from entering more than two digits after the decimal place (so that the content is saved as a currency and also just because i think it's important that the user is clear about what they're entering).

However i don't have much programming experience and i don't know where to start looking (validation is a pretty huge topic haha). A bit of googling and it sounds like i should make my own extension of the InputFilter class but i'm not sure how to go about that or if there's a better way. So Any advice would really be appreciated!

Holly
  • 1,956
  • 6
  • 41
  • 57

3 Answers3

2

Use the InputFilter http://developer.android.com/reference/android/text/InputFilter.html

Will Tate
  • 33,439
  • 9
  • 77
  • 71
  • yeah that's what i was thinking. I'd have to create my own class that extends it right? I'm not sure how to go about writing my own method for something like this.. Don't suppose you know of any examples or could explain to me how to start off? Thanks anyway – Holly Jan 22 '11 at 18:25
  • There is an example here: http://stackoverflow.com/questions/3349121/how-do-i-use-inputfilter-to-limit-characters-in-an-edittext-in-android Except your CharacterSequence would be a little more complicated. But the basic implementation of an InputFilter for an EditText is all there. – Will Tate Jan 22 '11 at 18:34
0

Try this

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

DecimalDigitsInputFilter

public class DecimalDigitsInputFilter implements InputFilter {
    Pattern mPattern;
    public DecimalDigitsInputFilter(int digitsAfterZero) {
        mPattern=Pattern.compile("[0-9]+((\\.[0-9]{0," + (digitsAfterZero-1) + "})?)||(\\.)?");
    }
    @Override
    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {

        Matcher matcher=mPattern.matcher(dest);       
        if(!matcher.matches())
            return "";
        return null;
    }
}
Kosh
  • 6,140
  • 3
  • 36
  • 67
sandeepmaaram
  • 4,191
  • 2
  • 37
  • 42
  • 2
    The logic in this prevents text from being added if the edittext already has a decimal. Example 1.45 will not be allowed to enter new text to something like 11.45. – Matthew Dec 12 '16 at 03:35
-1

To limit the user from not entering more than two digits after decimal point just use the following code.

myEditText1 = (EditText) findViewById(R.id.editText1);  
myEditText1.setInputType(3);

The number '3' does the trick. Hope it helps!