Search code examples
androidandroid-fragmentsandroid-actionbarandroid-appcompatandroid-homebutton

ActionBar Home button - hide fragment and clear back stack


I would like to implement Home/Up button in the actionBar. I have simple application with one Activity (A) and two fragments (Settings (B) and About (C)).

In the other questions I have found to use popBackStack, but that's not the solution bacause if user goes A > B > C > B > C, back-button goes C > B > C > B > A (is this correct behaviour?).

    switch (item.getItemId()){
        case R.id.action_settings:
            // get preferences fragment
            getFragmentManager().beginTransaction()
                    .replace(android.R.id.content, new PrefFragment())
                    .addToBackStack(null)
                    .commit();
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            return true;
        case R.id.action_about:
            // get about fragment
            getFragmentManager().beginTransaction()
                    .replace(android.R.id.content, new AboutFragment())
                    .addToBackStack(null)
                    .commit();
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            return true;
        case android.R.id.home:
            // clear back stack and show home screen?

            getSupportActionBar().setDisplayHomeAsUpEnabled(false);
            return true;
    }

I would need last case to hide any fragment (show main activity window) and clear my back stack - go home, not back. How could I achieve that?

I use AppCompat library.


Solution

  • try this:

     private void clearBackStack() {
        FragmentManager manager = getSupportFragmentManager();
        if (manager.getBackStackEntryCount() > 0) {
            FragmentManager.BackStackEntry first = manager.getBackStackEntryAt(0);
             manager.popBackStack(first.getId(), FragmentManager.POP_BACK_STACK_INCLUSIVE);
        }
    }
    

    or call

    mFragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE); 
    

    Form the documentation POP_BACK_STACK_INCLUSIVE is

    Flag for popBackStack(String, int) and popBackStack(int, int): If set, and the name or ID of a back stack entry has been supplied, then all matching entries will be consumed until one that doesn't match is found or the bottom of the stack is reached.