How to Set the Edittext Keyboard to Only Consist of Numbers on Android

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

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:

Sample Image

Android EditText - Input with numbers only

It seems to work well with this configuration:

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

That's a good enough workaround for me.

How do you set EditText to only accept numeric values in Android?

Add android:inputType="number" as an XML attribute.

How to force EditText to accept only numbers?

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

Android: Edittext that only allows a digit from 1-9

Ther have two ways for your question
1) in your XML fayl

<EditText
android:id="@+id/edittext"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:digits="123456789"
android:inputType="number"
android:maxLength="1"/>

2) in your Activity class

    mEdit.setInputType(InputType.TYPE_CLASS_NUMBER );
mEdit.setKeyListener(DigitsKeyListener.getInstance("0123456789"));
mEdit.setSingleLine(true);

Display keyboard for numers when inputType set to 'text'

You can use this but you need to handle invalid input yourself or add TextWatcher to check for input while typing

android:inputType="number"
android:digits="0123456789,."

How to force EditText to accept only numbers?

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



Related Topics



Leave a reply



Submit