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


当前回答

我想做一些类似的事情。但是从edit text中获取文本值并像(str=="")那样进行比较对我来说并不管用。所以更好的选择是:

EditText eText = (EditText) findViewById(R.id.etext);

if (etext.getText().length() == 0)
{//do what you want }

效果很好。

其他回答

这个函数对我有用

private void checkForm() {
    EditText[] allFields = {
        field1_txt,
        field2_txt,
        field3_txt,
        field4_txt
    };
    
    List < EditText > ErrorFields = new ArrayList < EditText > (); 

    for (EditText edit: allFields) {
        if (TextUtils.isEmpty(edit.getText())) {

            // EditText was empty
            ErrorFields.add(edit); //add empty Edittext only in this ArayList
            
            for (int i = 0; i < ErrorFields.size(); i++) {
                EditText currentField = ErrorFields.get(i);
                currentField.setError("this field required");
                currentField.requestFocus();
            }
        }
    }
}

我使用TextUtils来做这个:

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

我曾经做过类似的事情;

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;
}
private boolean hasContent(EditText et) {
       return (et.getText().toString().trim().length() > 0);
}