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


当前回答

这个函数对我有用

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

其他回答

我使用这个方法,使用trim()来避免空格:

EditText myEditText = (EditText) findViewById(R.id.editUsername);
if ("".equals(myEditText.getText().toString().trim()) {
    Toast.makeText(this, "You did not enter a value!", Toast.LENGTH_LONG).show();
    return;
}

一个例子,如果你有几个EditText´

if (("".equals(edtUser.getText().toString().trim()) || "".equals(edtPassword.getText().toString().trim()))){
        Toast.makeText(this, "a value is missing!", Toast.LENGTH_LONG).show();
        return;
}

试试这个吧: 它在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()
    }
}

谢谢你!

使用这段简短的代码,您可以删除字符串开头和结尾的空白。如果字符串是“”,则返回消息“error”,否则就是字符串

EditText user = findViewById(R.id.user); 
userString = user.getText().toString().trim(); 
if (userString.matches("")) {
    Toast.makeText(this, "Error", Toast.LENGTH_SHORT).show();
    return; 
}else{
     Toast.makeText(this, "Ok", Toast.LENGTH_SHORT).show();
}

这个函数对我有用

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 edt=(EditText)findViewById(R.id.Edt);

String data=edt.getText().toString();

if(data=="" || data==null){

 Log.e("edit text is null?","yes");

}

else {

 Log.e("edit text is null?","no");

}

对所有五个编辑文本都这样做吗