The input type of EditText in Android can be restricted. We can set it to input numbers only. There are the following types of numbers that we can set the EditText to input

  • Unsigned Integer
  • Signed Integer
  • Unsigned Decimal
  • Signed Decimal
We will learn how to do this using XML and programmatically using java code.

Unsigned Integer

XML

To set the EditText to input unsigned integer, you can set the input type to number in XML.


<EditText
....
android:inputType="number"
/>

Java Code

Add the following import:

import android.text.InputType;

Then call the setInputType function on EditText object with InputType.TYPE_CLASS_NUMBER parameter.

editText.setInputType(InputType.TYPE_CLASS_NUMBER);

Signed Integer (or simply Integer)

XML

Set the input type to numberSigned
<EditText
...
 android:inputType="numberSigned"
/>

Java Code

Add the import to android.text.InputType and then call the setInputType function with a type and a flag as a parameter as follows:

editText.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_SIGNED);


Unsigned Decimal

XML

Set the input type to numberDecimal as follows:


<EditText
...
android:inputType="numberDecimal"
/>

Java Code

Add import for InputType and call the setInputType function on EditText object with type and a flag joined with Bitwise OR operator ( | ) as follows:

editText.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);


Signed Decimal

XML

Set the type to numberSigned and numberDecimal. Both are joined by the OR operator ( | )

<EditText
...
android:inputType="numberSigned | numberDecimal"
/>

Java Code

Call the setInputType function on EditText object with one type and two flags joined by bitwise OR operator as a parameter.

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


Where to add the XML and Java Codes?

XML code is to be added in the XML file on an empty line inside angle brackets as shown in the screenshot below:
activity_main.xml
activity_main.xml

For Java code, first, find the EditText object using findViewByID method and call the function on the object. This is also shown in the screenshot below:
MainActivity.java
MainActivity.java