Android EditText 如何只接受整数或浮点值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11149881/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can EditText accept only integer or float value?
提问by void pointer
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?
我是 Android 开发的新手。在我的项目中,我使用 EditText,但我想强制它只接受整数或浮点值。我怎样才能做到这一点?
回答by K_Anas
If you want to use Decimal Numberonly on your EditText
如果您只想在您的设备上使用十进制数EditText
use the xml attribute android:inputType="numberDecimal"
in your EditText widget
your EditText
declaration will be like this:
android:inputType="numberDecimal"
在 EditText 小部件中使用 xml 属性,您的EditText
声明将如下所示:
<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 Numberthan combine the two Xml attributes android:inputType="numberDecimal"
and android:inputType="numberSigned"
. Your EditText
declaration will be like this:
如果您想使用有符号十进制数而不是将两个 Xml 属性android:inputType="numberDecimal"
和 android:inputType="numberSigned"
. 你的EditText
声明将是这样的:
<EditText
android:id="@+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="numberDecimal|numberSigned" >
</EditText>
回答by Phan Van Linh
Use Java
使用 Java
for input both integer and floatedit.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
用于输入整数和浮点数edit.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
for input only integeredit.setInputType(InputType.TYPE_CLASS_NUMBER);
仅用于输入整数edit.setInputType(InputType.TYPE_CLASS_NUMBER);
回答by Thalles
Currently using android tag:inputType is not enough.
目前使用 android tag:inputType 是不够的。
You need create a PreferenceChangeListener to verify the filled in EditText, before preference changed.
在首选项更改之前,您需要创建一个 PreferenceChangeListener 来验证填充的 EditText。