简体   繁体   中英

Android edittext - do not allow decimal separator alone

I have an Edittext, where I want to allow only numbers and decimal numbers (max 2 decimals after separator eg 125.50).

I implemented a filter for this:

 final EditText  field1 = (EditText)findViewById(R.id.field1);
 field1.setFilters(new InputFilter[] { filter });

    InputFilter filter = new InputFilter() {
        final int maxDigitsBeforeDecimalPoint=5;
        final int maxDigitsAfterDecimalPoint=2;

        @Override
        public CharSequence filter(CharSequence source, int start, int end,
                                   Spanned dest, int dstart, int dend) {
            StringBuilder builder = new StringBuilder(dest);
            builder.replace(dstart, dend, source
                    .subSequence(start, end).toString());
            if (!builder.toString().matches(
                    "(([0-9]{1})([0-9]{0,"+(maxDigitsBeforeDecimalPoint-1)+"})?)?(\\.[0-9]{0,"+maxDigitsAfterDecimalPoint+"})?"

            )) {
                if(source.length()==0)
                    return dest.subSequence(dstart, dend);
                return "";
            }

            return null;

        }
    };

This is working fine , but the problem is, that if user inserts decimal separator ALONE, I've got java.lang.NumberFormatException: For input string: "."

In my ontextChanged I tried this:

 if(field1.getText().toString().equals("[.]")){field1.setText(0);}

also this

if(field1.getText().toString().equals(".")){field1.setText(0);}

but did not work.

How can I restrict the decimal separator alone, but allow it with the numbers?

If this:

if(field1.getText().toString().equals(".")){field1.setText(0);}

is your exact code, then for sure it failed because 0 is not a string, it's an integer considered to be a resource id.
So first try this:

if(field1.getText().toString().equals(".")){field1.setText("0");}

If it fails again then consider that a NumberFormatException can be resolved by try/catch like this:

double value = 0.0;
try {
    value = Double.parseDouble(field1.getText().toString());
} catch (NumberFormatException e) {
    field1.setText("0");
    e.printStackTrace();
}

For References, you can use this link if you want to use InputFilter: https://stackoverflow.com/a/5368816/10396176

For other references, if you want using want to try using textWatcher: https://stackoverflow.com/a/16684661/10396176

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM