How can EditText accept only integer or float valu

2019-03-14 14:16发布

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?

3条回答
成全新的幸福
2楼-- · 2019-03-14 14:34

Currently using android tag:inputType is not enough.

See example https://github.com/udacity/ud851-Exercises/tree/student/Lesson06-Visualizer-Preferences/T06.10-Exercise-EditTextPreferenceConstraints

You need create a PreferenceChangeListener to verify the filled in EditText, before preference changed.

查看更多
倾城 Initia
3楼-- · 2019-03-14 14:35

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>
查看更多
啃猪蹄的小仙女
4楼-- · 2019-03-14 14:56

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);

查看更多
登录 后发表回答