2

I'm making an application that can control weight (kilogram). I have an edittext that can accept enter decimal numbers using:

et_beratbadan.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL | InputType.TYPE_NUMBER_FLAG_SIGNED);

my edittext already able to limit entering numbers, 3 digits before zero and 1 digit after zero (120.1) using:

et_beratbadan.setFilters(new InputFilter[]{new DecimalDigitsInputFilter(3, 1)});

what i want is, my edittext able to limit entering numbers, 3 digits before zero and 1 digit after zero, not accept minus values and start from one.

so it would allow : 123.4, 12.3, 1.2 not allow : 0, -12.3, 0.1

i already try code from https://stackoverflow.com/a/38793820 to make my edittext do not accept minus value. and some other code, that i lost the link for it.

and i have a class for implement inputfilter:

    public class DecimalDigitsInputFilter implements InputFilter {

private int mDigitsBeforeZero;
private int mDigitsAfterZero;
private Pattern mPattern;

private static final int DIGITS_BEFORE_ZERO_DEFAULT = 100;
private static final int DIGITS_AFTER_ZERO_DEFAULT = 100;

public DecimalDigitsInputFilter(Integer digitsBeforeZero, Integer digitsAfterZero) {
    this.mDigitsBeforeZero = (digitsBeforeZero != null ? digitsBeforeZero : DIGITS_BEFORE_ZERO_DEFAULT);
    this.mDigitsAfterZero = (digitsAfterZero != null ? digitsAfterZero : DIGITS_AFTER_ZERO_DEFAULT);
    mPattern = Pattern.compile("-?[0-9]{0," + (mDigitsBeforeZero) + "}+((\\.[0-9]{0," + (mDigitsAfterZero)
            + "})?)||(\\.)?");
}

@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
    String replacement = source.subSequence(start, end).toString();
    String newVal = dest.subSequence(0, dstart).toString() + replacement
            + dest.subSequence(dend, dest.length()).toString();
    Matcher matcher = mPattern.matcher(newVal);
    if (matcher.matches())
        return null;

    if (TextUtils.isEmpty(source))
        return dest.subSequence(dstart, dend);
    else
        return "";
}

}

sorry I'm still learning English and java. thanks!

dwiky
  • 59
  • 1
  • 5
  • The regex needed to do that is this `^[1-9]\d{0,2}(?:\.\d?)?$` Is regex something you need ? –  Jul 02 '19 at 20:12
  • thanks for answering my question. by the way, i found some (bug) when i use your code. if i input value then delete it before pressing the button, it the first value wouldn't deleted. something like this. input = 200 then delete, but 2 can't be deleted. @sln – dwiky Jul 03 '19 at 23:33
  • I don't know how you're using it, but it looks like you want to allow the empty string, which is ok, and is done like `^(?:[1-9]\d{0,2}(?:\.\d?)?)?$` –  Jul 03 '19 at 23:40

0 Answers0