我在android中有5个EditTexts。我想知道我是否可以检查所有5个EditTexts是否为空。有什么办法可以做到吗?


当前回答

if ( (usernameEditText.getText()+"").equals("") ) { 
    // Really just another way
}

其他回答

我通常按SBJ的建议去做,但反过来。我只是发现,通过检查阳性结果而不是双重否定,更容易理解我的代码。 您可能会询问如何检查空EdiTexts,但您真正想知道的是它是否有任何内容,而不是它是否为空。

像这样:

private boolean hasContent(EditText et) {
    // Always assume false until proven otherwise
    boolean bHasContent = false; 

    if (et.getText().toString().trim().length() > 0) {
        // Got content
        bHasContent = true;
    }
    return bHasContent;
}

作为SBJ,我更喜欢返回“没有内容”(或false)作为默认值,以避免异常,因为我取消了内容检查。这样,你就可以绝对确定,你的检查已经“批准”了一个true。

我还认为if调用它看起来也更简洁:

if (hasContent(myEditText)) {
// Act upon content
} else {
// Got no content!
}

这在很大程度上取决于个人偏好,但我发现这更容易阅读。:)

尝试使用If ELSE If条件。您可以轻松地验证editText字段。

 if(TextUtils.isEmpty(username)) {
                userNameView.setError("User Name Is Essential");
                return;
         } else  if(TextUtils.isEmpty(phone)) {
                phoneView.setError("Please Enter Your Phone Number");
                return;
            }

我曾经做过类似的事情;

EditText usernameEditText = (EditText) findViewById(R.id.editUsername);
sUsername = usernameEditText.getText().toString();
if (sUsername.matches("")) {
    Toast.makeText(this, "You did not enter a username", Toast.LENGTH_SHORT).show();
    return;
}

这里的派对已经晚了,但我只需要添加Android自己的TextUtils。isEmpty (CharSequence进行str)

如果字符串为null或0-length则返回true

所以如果你把你的五个edittext放在一个列表中,完整的代码将是:

for(EditText edit : editTextList){
    if(TextUtils.isEmpty(edit.getText()){
        // EditText was empty
        // Do something fancy
    }
}

如果editText为空,试试另一种简单的方法:

String star = editText.getText().toString();

if (star.equalsIgnoreCase("")) {
  Toast.makeText(getApplicationContext(), "Please Set start no", Toast.LENGTH_LONG).show();
}