Android: Limiting EditText to numbers

2019-01-27 14:57发布

问题:

When creating an EditText in the java portion of the application, how do you limit it to numbers like you would in the xml? For example:

new EditText(this);

set like

<EditText
    android:id="@+id/h1"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:inputType="numberDecimal"/>

回答1:

Something like this perhaps ?

EditText text = new EditText(this);
text.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL);


回答2:

Use of android:numeric is deprecated, use android:inputType=number



回答3:

Go to the docs and look at the table with XML attributes. It shows you the code equivalent of each item.

In this case, it's setRawInputType.



回答4:

this will usually do it:

android:numeric="integer"