java Android:将 EditText 限制为数字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5200689/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 09:55:15  来源:igfitidea点击:

Android: Limiting EditText to numbers

javaandroidandroid-edittext

提问by Biggsy

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:

在应用程序的 java 部分创建 EditText 时,如何像在 xml 中那样将其限制为数字?例如:

new EditText(this);

set like

设置像

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

回答by tacone

Something like this perhaps ?

也许是这样的?

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

回答by DevZer0

Use of android:numericis deprecated, use android:inputType="number"

使用android:numeric已过时,使用android:inputType="number"

回答by EboMike

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

转到文档并查看带有 XML 属性的表格。它显示了每个项目的等效代码。

In this case, it's setRawInputType.

在这种情况下,它是setRawInputType.

回答by NJGUY

this will usually do it:

这通常会这样做:

android:numeric="integer"

android:numeric="integer"

回答by Mahmoud Zaher

Simply use the below lines in the xmlfile

只需在xml文件中使用以下几行

To accept only Numbers put:

只接受数字放:

 android:inputType="number"

To limit the length of the input numbers:

要限制输入数字的长度:

android:maxLength="10"

To accept only specific numbers:

只接受特定数字:

EX:1The below line accept only 1 or 0.

EX:1下面的行只接受 1 或 0。

android:digits="10"

EX:2The below line accept only 2 or 3.

EX:2下面的行只接受 2 或 3。

android:digits="23"