Search code examples
androidnavigationfragmentfragmentmanager

Android Navigation Drawer with many fragments


I've been struggling with this for a while now, I want to start off with a diagram of my problem:

enter image description here

The three navigation drawer buttons are part of my Base Activity. Each purple block below the three buttons are fragments, and the descendants of each of those blocks are in turn fragments. I'll use the master and detail fragments as a demonstration of the issue I am having...The user clicks the nav drawer button, which opens the master fragment that hosts a list of articles. Once a user clicks one of those articles, I then open the detail fragment inside of the master fragment. So If I find myself at the detail, and I decide to open the nav drawer and click the third button for instance, then click the second button again, I want the detail to be open still, and if I hit the phone's back button I want it to move back to the master fragment, and end there. Any tips will be helpful, as I am probably going to use a similar pattern for the first button, it's main fragment and it's children fragments as well.


Solution

  • In my opinion, the cleanest way to handle what you are describing would be to have three separate FragmentActivity classes that implement the DrawerLayout instead of one monolithic BaseActivity.

    Each button in the drawer should start it's respective FragmentActivity using launchMode singleTask. This ensures that you launch the same activity instance each time, instead of a new one, which will maintain your back stack for each activity as you switch between them using the drawer buttons. See Android Developer Guide Activity:launchMode for more details.

    Each of the three FragmentActivity instances should be responsible for starting and managing it's fragments using listener interfaces. For example, where you have your Master fragment opening a Detail fragment directly, you should instead have your Master fragment tell it's FragmentActivity that it needs to open the Detail fragment. See Android Developer Guide: Communicating with Other Fragments for recommended practices in implementing this type of decoupled communication between FragmentActivity and Fragment. It will make your life much easier down the road when you want different layouts for tablets, etc.

    Each of the three main drawer "tasks" seem to be unique enough that isolating each within it's own FragmentActivity seems the best way to implement what you are trying to do. You can apply this same approach for each of your main sections.