Processing decimal places Edittext

Asked

Viewed 547 times

0

I need to set a number of decimals for a EditText on Android. For this I used a InputFilter as shown below:

public NumeroFormatado(int digitsBeforeZero,int digitsAfterZero) 
{
    mPattern=Pattern.compile("[0-9]{0," + (digitsBeforeZero - 1) + "}+((\\.[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;
}

And in my Activity I define:

editValor = (EditText) findViewById(R.id.editValor);
editValor.setFilters(new InputFilter[] {new NumeroFormatado(10,2)});

But when I report a value as for example 22.85 and click on the button next to the keyboard, the field loses the decimals. If I inform 22.80 works normally.

1 answer

1


All it took was an adjustment InputFilter and the class was as shown below:

public class NumeroFormatado 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 NumeroFormatado(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 "";
 }
}

In the Activity continues the same call:

editValor = (EditText) findViewById(R.id.editValor);
editValor.setFilters(new InputFilter[] {new NumeroFormatado(10,2)});
  • Thank you there for your reply. It was exactly what I was looking for!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.