Exit app when press Back button in activity with multiple fragments in Navigation Drawer

just exit the app at second last screen

  public void onBackPressed() {

    if (manager.getBackStackEntryCount() > 1 ) {
        // If there are back-stack entries, leave the FragmentActivity
        // implementation take care of them.
        manager.popBackStack();

    } else {
        // Otherwise, ask user if he wants to leave :)
        new AlertDialog.Builder(this)
                .setTitle("Really Exit?")
                .setMessage("Are you sure you want to exit?")
                .setNegativeButton(android.R.string.no, null)
                .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface arg0, int arg1) {
                        MainActivity.super.onBackPressed();
                    }
                }).create().show();
    }
}

Remove addToBackStack() from your Fragment A. Hope that helps.


I guess I am the one with the other unanswered question, so I want to show you my workaround:

I check if there is one child in my FrameLayout. If there is one, I will go one fragment back. And check again. Because I do only know the whitescreen for sure, I need to check after it for 0 childs left. If there exist still another fragment, there is nothing to do anymore, but if childs == 0, you want to ask for leaving the activity.

Alternatively you can remove the AlertDialog and close the app if you reach this last fragment.

@Override
public void onBackPressed() {
    FrameLayout fl = (FrameLayout) findViewById(R.id.content_frame);
    if (fl.getChildCount() == 1) {
        super.onBackPressed();
        if (fl.getChildCount() == 0) {
            new AlertDialog.Builder(this)
                    .setTitle("Close App?")
                    .setMessage("Do you really want to close this beautiful app?")
                    .setPositiveButton("YES",
                            new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog,
                                        int which) {
                                    finish();
                                }
                            })
                    .setNegativeButton("NO",
                            new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog,
                                        int which) {
                                }
                            }).show();
            // load your first Fragment here
        }
    } else if (fl.getChildCount() == 0) {
        // load your first Fragment here
    } else {
        super.onBackPressed();
    }
}