Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can EditText accept only integer or float value?

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?

like image 641
void pointer Avatar asked Jun 22 '12 03:06

void pointer


People also ask

How do I get float in EditText?

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.

How can add only numbers in EditText in android?

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 .

How do you make EditText read only?

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.

How do I change my EditText value?

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.


2 Answers

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> 
like image 99
K_Anas Avatar answered Sep 19 '22 14:09

K_Anas


Use Java

for input both integer and float
edit.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);

for input only integer
edit.setInputType(InputType.TYPE_CLASS_NUMBER);

like image 34
Linh Avatar answered Sep 18 '22 14:09

Linh