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


当前回答

试试这个吧: 它在Kotlin

//button from xml
button.setOnClickListener{                                         
    val new=addText.text.toString()//addText is an EditText
    if(new=isNotEmpty())
    {
         //do something
    }
    else{
        new.setError("Enter some msg")
        //or
        Toast.makeText(applicationContext, "Enter some message ", Toast.LENGTH_SHORT).show()
    }
}

谢谢你!

其他回答

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

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

您可以使用EditText中的length()。

public boolean isEditTextEmpty(EditText mInput){
   return mInput.length() == 0;
}

对于验证EditText使用edittext# setError方法来显示错误,对于检查空值或空值使用内置的android类TextUtils.isEmpty(strVar),如果strVar为空或零长度返回true

EditText etUserName = (EditText) findViewById(R.id.txtUsername);
String strUserName = etUserName.getText().toString();

 if(TextUtils.isEmpty(strUserName)) {
    etUserName.setError("Your message");
    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;
}