Search code examples
androidandroid-listfragmentback-stack

Android - Managing fragment swapping


My application has an activity A which on creation loads a ListFragment -> Fa.

On selecting one of the items, Fa is added to the BackStack and is replaced with another instance of Fa with a different set of data.

Selecting an item in this new instance of Fa puts it into BackStack and replaces it with a third ListFragment -> Fb, whose layout is different.

Fb is designed to show list in a paginated manner and has 2 buttons at its bottom, (Previous) and (Next).

Now I want that when user clicks on the next button I should display the next page of list using a new instance of Fb, but i do not want to add its previous instance to backstack, so that when user presses the back button on the device, he should be taken to second instance of Fa and not the previous instance of Fb.

I was able to achieve all the forward traversing bits as well as the previous and next button tasks, but now when i press the back button, the second instance of Fa shows up however Fb's last instance does not get removed and can be seen in the background.

How can i remove all instances of Fb and show only Fa when i press the back button.


Solution

  • You could override the Back button behaviour and 'pop' the back stack up to the desired fragment:

    @Override
    public void onBackPressed() {
        fragmentManager.popBackStack(R.id.fragmentA, 0);
    }
    

    popBackStack will consume all fragments until it reaches the one which is supplied when called.