How can EditText accept only integer or float value?

故事扮演 提交于 2019-12-03 08:29:47

问题


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?


回答1:


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>



回答2:


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




回答3:


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.



来源:https://stackoverflow.com/questions/11149881/how-can-edittext-accept-only-integer-or-float-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!