Search code examples
androidfragmentmaster-detail

Remove fragments from detail view


I wanted to remove fragments(stack of fragments) from a master-detail's Detail view. If i click on a list item in the master view, it opens up a fragment, if i edit the list view's item another fragment is used. What i want to do is, remove all the fragments from the detail view changing it to a blank container, as it is when the app starts up.

Currently i am replacing the container with a blank fragment, but it does not work in few detail view cases.

NullFragment fragment = new NullFragment();
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager
        .beginTransaction();
fragmentTransaction.replace(R.id.item_detail_container,
        fragment);
fragmentManager.popBackStackImmediate();
fragmentTransaction.commit();

Solution

  • You can use FragmentManager.getBackStackEntryCount() to get number of fragments in backstack and use FragmentManager.popBackStack() to pop the top fragment in stack one-by-one.