简体   繁体   English

如何验证在edittext中输入的数字? - 安卓

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

well am able to validate an edittext when its empty using the below code当它为空时,我能够使用下面的代码验证一个edittext

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

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

the edittext input 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!帮帮我! :) :)

You can do something like that:你可以这样做:

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

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

Integer.parseInt(a.getText())

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

Then you can just do a comparison: if( val < min || val > max ) //show message ;然后你可以做一个比较: if( val < min || val > max ) //show message ;

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(".");
    }

You can do something like that:你可以这样做:

First check Edittext is null Second check Edittext is value grater than 0首先检查 Edittext 是否为 null 第二次检查 Edittext 的值大于 0

String amount1 = edtAmount1.getText().toString().trim();
            if( amount1.length() == 0 || Double.valueOf(amount1)<1){
                Toast.makeText(StudentfeepayActivity.this,"Enter fee amount",Toast.LENGTH_LONG).show();
                return;
            }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM