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


当前回答

private boolean hasContent(EditText et) {
       return (et.getText().toString().trim().length() > 0);
}

其他回答

我通常按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(searchText.getText().toString().equals("")) 
    Log.d("MY_LOG", "Empty");

首先,我从EditText检索文本,然后将其转换为字符串,最后使用.equals方法将其与“”进行比较。

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

我曾经做过类似的事情;

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;
}

我使用TextUtils来做这个:

if (TextUtils.isEmpty(UsernameInfo.getText())) {
    validationError = true;
    validationErrorMessage.append(getResources().getString(R.string.error_blank_username));
}