Home > database >  Allow only one decimal point in EditText
Allow only one decimal point in EditText

Time:12-22

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

CodePudding user response:

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

CodePudding user response:

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