如何限制 EditText 在 Java 中只输入浮点值?

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

How to limit EditText to input only float values in Java?

javaandroidandroid-edittext

提问by Ayush Goyal

I have found answers to limit it to Integer/float in xml, I want to do it programmatically. I can set setInputType(InputType.TYPE_CLASS_NUMBER)for integer values, but what for float values?

我找到了将其限制为 xml 中的整数/浮点数的答案,我想以编程方式进行。我可以设置setInputType(InputType.TYPE_CLASS_NUMBER)整数值,但是浮点值呢?

I want them in xxxx.xxxformat.

我想要它们的xxxx.xxx格式。

回答by Chandra Sekhar

I think you are looking for

我想你正在寻找

android:inputType="numberDecimal"

in the xml file and

在 xml 文件和

InputType.TYPE_NUMBER_FLAG_DECIMAL

in the java source file.

在java源文件中。

TYPE_NUMBER_FLAG_DECIMALis a flag of TYPE_CLASS_NUMBERand allows decimal inputs.

TYPE_NUMBER_FLAG_DECIMAL是一个标志TYPE_CLASS_NUMBER并允许小数输入。

For more information see this

有关更多信息,请参阅

In another way you can test the input value using

在另一种方式中,您可以使用测试输入值

if(editText.getText().toString().contains("."))
     //Its a float value
else
     //Not a float value

回答by Pradeep Kumar Kushwaha

Well simply use

那么简单地使用

editText.setInputType(InputType.TYPE_CLASS_NUMBER|InputType.TYPE_NUMBER_FLAG_DECIMAL)

editText.setInputType(InputType.TYPE_CLASS_NUMBER|InputType.TYPE_NUMBER_FLAG_DECIMAL)

only if you want to do it programmatically.

仅当您想以编程方式进行时。