NiceToMytyuk
NiceToMytyuk

Reputation: 4277

Allow only one decimal point in EditText

I'm trying to add an InputFilter to my EditText which must allow only integers or decimal numbers with only one decimal point.

Accepted input must be:

1 - 12 - 3.33 - 4.20 etc.

Refused:

.0 - 5. - 5.5.5 - 40.21.1 etc.  

I've created a custom InputFilter which check if the input match following RegExp ^\d+(\.\d+)?$

But instead EditText always shows an empty string, in debug "spanned" is always empty while by default the EditText has a starting value.

Filter:

public class DecimalDigitsFilter implements InputFilter {
    @Override
    public CharSequence filter(CharSequence charSequence, int i, int i1, Spanned spanned, int i2, int i3) {
        Pattern pattern = Pattern.compile("^\\d+(\\.\\d+)?$");
        Matcher matcher = pattern.matcher(spanned);
        if (!matcher.matches()){
            return "";
        }
        return null;
    }
}

Activity:

quantita.setFilters(new InputFilter[] {new DecimalDigitsFilter()});

Upvotes: 0

Views: 72

Answers (2)

NiceToMytyuk
NiceToMytyuk

Reputation: 4277

I had to move mo logics in TextChangedListener as in InputFilter i wasn't able to get the whole string where to check my RegExp.

Furthermore i had even to change my RegExp a bit like this ^\d+(\.([\d+]+)?)?$ i had to set values after decimal point as optionable else the .matches() was going to fail every time i was writing a decimal point.

So the final code looks like this:

quantita.addTextChangedListener(new TextWatcher() {
    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void afterTextChanged(Editable editable) {
        Pattern pattern = Pattern.compile("^\\d+(\\.([\\d+]+)?)?$");
        Matcher matcher = pattern.matcher(quantita.getText().toString());
        if (!matcher.matches()){
            quantita.setText("");
        }
    }
});

Upvotes: 0

Tim Biegeleisen
Tim Biegeleisen

Reputation: 520898

You need to run the matcher against the actual text in the EditText:

public class DecimalDigitsFilter implements InputFilter {
    @Override
    public CharSequence filter(CharSequence charSequence, int i, int i1, Spanned spanned, int i2, int i3) {
        Pattern pattern = Pattern.compile("^\\d+(\\.\\d+)?$");
        Matcher matcher = pattern.matcher(spanned.getText());
        if (!matcher.matches()){
            return "";
        }

        return null;
    }
}

Upvotes: 1

Related Questions