Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I restrict my EditText input to numerical (possibly decimal and signed) input?

I have read Android: Limiting EditText to numbers and How do I show the number keyboard on an EditText in android?. Unfortunately, none of them seems to fit my needs.

I want to restrict my EditText input to only numbers. However, I also want to allow signed and/or decimal input.

Here is my current code (I need to do this programmatically):

EditText edit = new EditText(this);

edit.setHorizontallyScrolling(true);
edit.setInputType(InputType.TYPE_CLASS_NUMBER);

With this, my EditText merrily restricts all input to numerical digits. Unfortunately, it doesn't allow anything else, like the decimal point.

If I change that line to edit.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL), the EditText accepts all input (which isn't what I want...).

I've tried combining flags (in desperation to see if it would work):

edit.setInputType(InputType.TYPE_CLASS_NUMBER);
edit.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL)
edit.setInputType(InputType.TYPE_NUMBER_FLAG_SIGNED)

That didn't work either (the EditText accepted all input as usual).

So, how do I do this?

like image 225
kibibyte Avatar asked Aug 02 '11 22:08

kibibyte


3 Answers

There's no reason to use setRawInputType(), just use setInputType(). However, you have to combine the class and flags with the OR operator:

edit.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL | InputType.TYPE_NUMBER_FLAG_SIGNED);
like image 188
Ralf Avatar answered Oct 29 '22 14:10

Ralf


Try using TextView.setRawInputType() it corresponds to the android:inputType attribute.

like image 35
Dan S Avatar answered Oct 29 '22 13:10

Dan S


Use this. Works fine

input.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL | InputType.TYPE_NUMBER_FLAG_SIGNED);
input.setKeyListener(DigitsKeyListener.getInstance("0123456789"));

EDIT

kotlin version

fun EditText.onlyNumbers() {
    inputType = InputType.TYPE_CLASS_NUMBER or InputType.TYPE_NUMBER_FLAG_DECIMAL or
        InputType.TYPE_NUMBER_FLAG_SIGNED
    keyListener = DigitsKeyListener.getInstance("0123456789")
}
like image 21
Vlad Avatar answered Oct 29 '22 14:10

Vlad