I am new to Android development. In my project, I’m using EditText, but I want to force it to only accept an integer or float value. How can I do that?
You use the valueOf() method if the Float wrapper class to convert a string to a float. IN this example I get the Editable object of that EditText with getText() on which I call the toString() method to obtain a string from it.
You can use android:inputType="number" in the XML file. You can specify other values such as numberDecimal as well. Also, you might additionally want to use android:singleLine="true" for a single line Edittext .
The most reliable way to do this is using UI. setReadOnly(myEditText, true) from this library. There are a few properties that have to be set, which you can check out in the source code.
This example demonstrates how do I set only numeric value for editText in Android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml.
If you want to use Decimal Number only on your EditText
use the xml attribute android:inputType="numberDecimal"
in your EditText widget your EditText
declaration will be like this:
<EditText android:id="@+id/editText1" android:layout_width="match_parent" android:layout_height="wrap_content" android:ems="10" android:inputType="numberDecimal" />
If you want to use Signed Decimal Number than combine the two Xml attributes android:inputType="numberDecimal"
and android:inputType="numberSigned"
. Your EditText
declaration will be like this:
<EditText android:id="@+id/editText1" android:layout_width="match_parent" android:layout_height="wrap_content" android:ems="10" android:inputType="numberDecimal|numberSigned" > </EditText>
Use Java
for input both integer and floatedit.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
for input only integeredit.setInputType(InputType.TYPE_CLASS_NUMBER);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With