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
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
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
<EditText
…
android:inputType=“numberSigned”
/>
Java Code
editText.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_SIGNED);
Unsigned Decimal
XML
<EditText
…
android:inputType=“numberDecimal”
/>
Java Code
editText.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
Signed Decimal
XML
<EditText
…
android:inputType=“numberSigned | numberDecimal”
/>
Java Code
editText.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL | InputType.TYPE_NUMBER_FLAG_SIGNED);
Where to add the XML and Java Codes?
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 |