How to force EditText to accept only numbers?

AndroidAndroid Edittext

Android Problem Overview


how to force the EditText to accept only numbers.?

Android Solutions


Solution 1 - Android

Use android:inputType="number" in your layout XML

Solution 2 - Android

This also works fine:

android:digits="0123456789"

Solution 3 - Android

Or you can add the following:

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

this will accept numbers, float point numbers and negative numbers you can remove any of these as needed

Solution 4 - Android

You can use android:inputType="number" in the XML file. You can specify other values such as numberDecimal as well.

Also, you might additionally want to use android:singleLine="true" for a single line Edittext.

Also, look into android:numeric and android:maxLength. maxLength in particular can be useful for setting length limitations.

Solution 5 - Android

If you need support for decimal numbers use this:

  android:inputType="numberDecimal"

Solution 6 - Android

This is the final solution:

 public static void enforceEditTextUseNumberOnly(EditText field) {
        Typeface existingTypeface = field.getTypeface();
        field.setInputType((InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_VARIATION_PASSWORD));
        field.setTransformationMethod(new NumericKeyBoardTransformationMethod());
        field.setTypeface(existingTypeface);
        if (field.getParent().getParent() instanceof TextInputLayout) {
            ((TextInputLayout) field.getParent().getParent()).setPasswordVisibilityToggleEnabled(false);
        }
    }

  private static class NumericKeyBoardTransformationMethod extends PasswordTransformationMethod {
        @Override
        public CharSequence getTransformation(CharSequence source, View view) {
            return source;
        }
    }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser1125258View Question on Stackoverflow
Solution 1 - AndroidDenis BabakView Answer on Stackoverflow
Solution 2 - AndroidAlysson MyllerView Answer on Stackoverflow
Solution 3 - AndroidSergey BennerView Answer on Stackoverflow
Solution 4 - AndroidSamarView Answer on Stackoverflow
Solution 5 - AndroidGiedrius ŠlikasView Answer on Stackoverflow
Solution 6 - AndroidPier BetosView Answer on Stackoverflow