Monday, September 30, 2013

Back stack with nested fragments + back button

When you have fragments with nested fragments, the FragmentActivity which handles the BACK button will not properly handle the back stack of those nested fragments.

In my application, I'm using a ViewPager with some fragments, and only one of them has nested fragments added to the back stack. In this case, when someone tries to press the back button, the activity will not handle the nested fragment stack and will finish right away. To solve this problem, I've implemented the following hack to the FragmentActivity. Please note that the activity only has one back stack: this will not work properly when you have a ViewPager with multiple fragments adding/replacing fragments into the back stack as it will get messy when the stack is not in a desired order.