piavgh piavgh - 6 months ago 458
Android Question

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

I'm working on an app that need Navigation Drawer. This app has 1 MainActivity and about 10 fragments on it. When I click the Navigation Drawer icon in MainActivity it will show the 10 fragments so I can select each of them.

I choose fragment A, then B, then C...to F, for example. When I'm in fragment F and press the Back button, it will take me back to fragment E, then Back again it will take me to fragment D...

My problem is when I'm back to fragment A (from fragment B, of course) and press Back button one more time, it take me to a blank white screen (I think this is the main activity layout). And press Back one more time, the app will exit.

What I want is when I'm back to fragment A (last fragment) and hit Back, the app will exit immediately, not the blank white screen anymore

I've search on SO and found 1 similar question but no answer yet so I have to make another question

How can I do this?
Thank you very much

Answer

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