java 如何验证在编辑文本中输入的数字?- 安卓

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

How to validate a number entered in the edittext? - android

javaandroidvalidationnumbersandroid-edittext

提问by kumareloaded

well am able to validate an edittext when its empty using the below code

当编辑文本为空时,可以使用以下代码验证它

EditText a = (EditText) findViewById(R.id.edittext1); 

if ((a.getText().toString().equals(""))
{
    Toast.makeText(getApplicationContext(), "value is empty", 0).show();
}   

the edittextinput type is set as number.

所述的EditText输入类型被设定为编号。

now i want to validate the number entered.

现在我想验证输入的数字。

for example the range of number to be entered should be between 15 to 25.

例如,要输入的数字范围应在 15 到 25 之间。

if the number is below 15 or above 25 it should show Out of Range

如果数字低于 15 或高于 25,则应显示超出范围

help me out! :)

帮帮我!:)

回答by thomasg

You can do something like that:

你可以这样做:

final int value = Integer.valueOf(a.getText().toString());  
if (value < 15 || value > 25) {  
    // do what you want  
}

回答by Subir Kumar Sao

Parse the value to Integer or Float and do your validation.

将值解析为 Integer 或 Float 并进行验证。

Integer.parseInt(a.getText())

回答by Jave

If you know that the value entered is a number you can first parse it using either:
int val = Integer.parseInt(a.getText());
or if it is a float:
float val = Float.parseFloat(a.getText());.

如果您知道输入的值是一个数字,您可以首先使用以下任一方法解析它:
int val = Integer.parseInt(a.getText());
或者如果它是一个浮点数:
float val = Float.parseFloat(a.getText());

Then you can just do a comparison: if( val < min || val > max ) //show message;

然后你可以做一个比较:if( val < min || val > max ) //show message;

回答by Abhijeet Sharma

You can use this method to check decimal number is valid or not valid:

您可以使用此方法来检查十进制数是否有效:

public boolean isValidDecimalNumber(EditText editText) {
        return !TextUtils.isEmpty(editText.getText().toString().trim()) && !editText.getText().toString().trim().equalsIgnoreCase(".");
    }