Android:在Number / Phone上设置inputType时,检查EditText是否为空

问题描述 投票:14回答:7

我在android中有一个EditText供用户输入他们的AGE。它设置为inputType = phone。我想知道是否有办法检查这个EditText是否为空。

我已经看过这个问题了:Check if EditText is empty.但它没有解决inputType = phone的情况。

这些,我已经检查过并且不起作用:

(EditText) findViewByID(R.id.age)).getText().toString() == null
(EditText) findViewByID(R.id.age)).getText().toString() == ""
(EditText) findViewByID(R.id.age)).getText().toString().matches("")
(EditText) findViewByID(R.id.age)).getText().toString().equals("")
(EditText) findViewByID(R.id.age)).getText().toString().equals(null)
(EditText) findViewByID(R.id.age)).getText().toString().trim().length() == 0
(EditText) findViewByID(R.id.age)).getText().toString().trim().equals("")
and isEmpty do not check for blank space.

谢谢您的帮助。

android android-edittext gettext
7个回答
36
投票

您可以使用TextUtils类进行检查

TextUtils.isEmpty(ed_text);

或者您可以这样检查:

EditText ed = (EditText) findViewById(R.id.age);

String ed_text = ed.getText().toString().trim();

if(ed_text.isEmpty() || ed_text.length() == 0 || ed_text.equals("") || ed_text == null)
{
    //EditText is empty
}
else
{
    //EditText is not empty
}

7
投票

第一种方法

使用TextUtil库

if(TextUtils.isEmpty(editText.getText().toString()) 
{
    Toast.makeText(this, "plz enter your name ", Toast.LENGTH_SHORT).show();
    return;
}

第二种方法

private boolean isEmpty(EditText etText) 
{
        return etText.getText().toString().trim().length() == 0;
}

0
投票

我将此方法用于相同的工作:

public boolean checkIsNull(EditText... editTexts){
for (EditText editText: editTexts){
  if(editText.getText().length() == 0){
    return true;
  }
}
return false;
}

0
投票

只需执行以下操作

String s = (EditText) findViewByID(R.id.age)).getText().toString();
TextUtils.isEmpty(s);

0
投票

EditText textAge; textAge =(EditText)findViewByID(R.id.age); if(TextUtils.isEmpty(textAge)) { Toast.makeText(this,“Age Edit text is Empty”,Toast.LENGTH_SHORT).show(); //或在此输入您想要的代码 }


0
投票

我发现如果用户输入一个空格,这些测试会失败,所以我测试了空值的缺失提示

EditText username = (EditText) findViewById(R.id.editTextUserName);

EditText password = (EditText) findViewById(R.id.editTextPassword);

// these hint strings reflect the hints attached to the resources

if (username.getHint().equals("Enter your username") || password.getHint().equals("Enter Your Password")){
      // enter your code here 

} else {
      // alls well
}

-1
投票

试试这个。这是我得到的唯一解决方案

串电话;

尝试{phone =(EditText)findViewByID(R.id.age))。getText()。toString();

} catch(NumberFormatException e){

Toast.makeText(MainActivity.this,“plz enterphone Number”,Toast.LENGTH_SHORT).show();返回;

}

© www.soinside.com 2019 - 2024. All rights reserved.