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


当前回答

“看看这个,我相信你会喜欢的。”

log_in.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        username=user_name.getText().toString();
        password=pass_word.getText().toString();
        if(username.equals(""))
        {
            user_name.setError("Enter username");
        }
        else if(password.equals(""))
        {
            pass_word.setError("Enter your password");
        }
        else
        {
            Intent intent=new Intent(MainActivity.this,Scan_QRActivity.class);
            startActivity(intent);
        }
    }
});

其他回答

如果EditText为空,为什么不禁用按钮呢?恕我直言,这看起来更专业:

        final EditText txtFrecuencia = (EditText) findViewById(R.id.txtFrecuencia);  
        final ToggleButton toggle = (ToggleButton) findViewById(R.id.toggleStartStop);
        txtFrecuencia.addTextChangedListener(new TextWatcher() {
        @Override
        public void afterTextChanged(Editable s) {
            toggle.setEnabled(txtFrecuencia.length() > 0);
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                int count) {

        }
       });

试试这个

TextUtils.isEmpty(editText.getText());

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

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

这个函数对我有用

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

你也可以检查所有的EditText字符串在一个If条件:像这样

if (mString.matches("") || fString.matches("") || gender==null || docString.matches("") || dString.matches("")) {
                Toast.makeText(WriteActivity.this,"Data Incomplete", Toast.LENGTH_SHORT).show();
            }