简体   繁体   中英

Dialog dismiss on yes button

I'm using class that extends from dialog to change a password. When I press yes button the dialog is dismissed. I want the dialog to not dismiss if I have wrong inputs.

This my code

@Override
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.btn_yes:
            if ((!TextUtils.isEmpty(newpass.getText().toString())) && oldpass.getText().toString().equals(Login_Activity.e.getPassword())) {
                Login_Activity.e.password=newpass.getText().toString();
                user.child(Login_Activity.e.getId()).setValue(Login_Activity.e);
                dismiss();
            } else {
                yes.setBackgroundResource(R.color.red);
            }
        case R.id.btn_no:
            dismiss();
            break;
    }
}

Thanks for helping

You need to add break statement for case R.id.btn_yes . According to docs :

The break statements are necessary because without them, statements in switch blocks fall through: All statements after the matching case label are executed in sequence, regardless of the expression of subsequent case labels, until a break statement is encountered

In your situation, button with id btn_yes is clicked, then either block of code in if or else is executed then program flow continues to execution of code in case R.id.btn_no because it wasn't stopped with break in matching case.

@Override
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.btn_yes:
            if ((!TextUtils.isEmpty(newpass.getText().toString())) && oldpass.getText().toString().equals(Login_Activity.e.getPassword())) {
                Login_Activity.e.password=newpass.getText().toString();
                user.child(Login_Activity.e.getId()).setValue(Login_Activity.e);
                dismiss();
            } else {
                yes.setBackgroundResource(R.color.red);
            }
            break; // add this
        case R.id.btn_no:
            dismiss();
            break;
    }
}

You can override the auto-dismiss behaviour manually, depending on your dialog class.

The answers on this question offer several ways to achieve this, like replacing the button's onClick listener, or even disabling it dynamically if your inputs are invalid.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM