Search code examples
androidandroid-layoutandroid-edittext

How do you set the EditText keyboard to only consist of numbers on Android?


I want my EditText to display a keyboard that ONLY has numbers visible, no other characters.

I have tested with all available inputs and it doesn't work. I searched for a way to get a keyboard that only has numbers but I have only seen references to:

android: inputType = "numberPassword"

But I want the numbers to be visible, like this: (numberPassword)

enter image description here

I have tried with:

android:digits="0123456789"
android:inputType="phone"

and

android:inputType="number"

but it appears like this:

enter image description here


Solution

  • After several tries, I got it! I'm setting the keyboard values programmatically like this:

    myEditText.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_VARIATION_PASSWORD);
    

    Or if you want you can edit the XML like so:

    android:inputType="numberPassword"
    

    Both configs will display password bullets, so we need to create a custom ClickableSpan class:

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

    Finally we need to implement it on the EditText in order to display the characters typed.

    myEditText.setTransformationMethod(new NumericKeyBoardTransformationMethod());
    

    This is how my keyboard looks like now: