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


当前回答

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

        }
       });

其他回答

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

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 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");

}

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

试试这个:

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

你可以为每个编辑文本调用这个函数:

public boolean isEmpty(EditText editText) {
    boolean isEmptyResult = false;
    if (editText.getText().length() == 0) {
        isEmptyResult = true;
    }
    return isEmptyResult;
}

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

        }
       });