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


当前回答

我曾经做过类似的事情;

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

其他回答

试试这个:

EditText txtUserName = (EditText) findViewById(R.id.txtUsername);
String strUserName = usernameEditText.getText().toString();
if (strUserName.trim().equals("")) {
    Toast.makeText(this, "plz enter your name ", Toast.LENGTH_SHORT).show();
    return;
}

或者像这样使用TextUtils类:

if(TextUtils.isEmpty(strUserName)) {
    Toast.makeText(this, "plz enter your name ", Toast.LENGTH_SHORT).show();
    return;
}
if(TextUtils.isEmpty(textA.getText())){
            showToast(it's Null");
        }

你可以使用TextUtils。isEmpty就像我的例子! 祝你好运

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

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

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

以下几点对我来说很有用:

if(searchText.getText().toString().equals("")) 
    Log.d("MY_LOG", "Empty");

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

我通常按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!
}

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