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

其他回答

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

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

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

效果很好。

其他答案是正确的,但要用一种简短的方式

if(editText.getText().toString().isEmpty()) {
     // editText is empty
} else {
     // editText is not empty
}
if ( (usernameEditText.getText()+"").equals("") ) { 
    // Really just another way
}

如果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) {

        }
       });

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

谢谢你!