简体   繁体   中英

Prevent activity from closing due to click on Up/home in action bar?

How can I prevent the activity from being closed, if the user clicks on the Up/Home button (in the action bar, not the physical one)? I tried to do something like this as a first approach, but even the modal dialog is swept away:

@Override
public boolean onOptionsItemSelected(final MenuItem item) {

    final int id = item.getItemId();
    if (android.R.id.home == id) {

        (new AlertDialog.Builder(this))
                .setMessage("Do you really want to quit ?")
                .setPositiveButton("Yes",
                        new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                // @TODO: don't stop activity
                dialog.dismiss();
            }

        }).setNegativeButton("Cancel",
                        new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // @TODO: stop activity
                        dialog.dismiss();
                    }}).show();
    }
    return super.onOptionsItemSelected(item);
}

Here's an example. The code explains itself.

@Override
public boolean onOptionsItemSelected(final MenuItem item) {
    final int id = item.getItemId();
    if (android.R.id.home == id) {
        (new AlertDialog.Builder(this))
                .setMessage("Do you really want to quit ?")
                .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        finish(); // finish activity
                    }
                })
                .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .show();
        return true; // true = handled manually (consumed)
    } else {
        // Default behaviour for other items
        return super.onOptionsItemSelected(item);
    }
}

在OptionsItemSelected中,如果在每个按钮的每个switch case语句中返回true而不是构造函数,那么您的行为将是运行的行为,而不是默认行为。

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