Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Master/Detail flow inside ViewPager

I have encountered a problem which i'm unable to solve, I googled a lot but couldn't find a solution.

In my app I have a ViewPager which contains 3 pages. These pages are fragments as they should be. This works alright. However two of these pages must be Master/Detail flows (one for friends list, one for news feed). When I create a master/detail flow with eclipse 2 fragments and 2 activities are created. The ItemListActivity (the one that needs to be shown) implements the fragment's Callbacks, and this is an Activity, but ViewPager only accepts Fragments inside itself.

So the question is: How can I place Master/Detail Flow inside a ViewPager?

All help is much appreciated! I'm all out of ideas here.

Thanks

like image 406
Gergely Sallai Avatar asked Jan 27 '13 12:01

Gergely Sallai


1 Answers

Master/Detail Flow is just a nickname for 2 fragments being used in the same content view, one on the left and one on the right. That's the general idea. Now, the Master/Detail Flow can be used inside an Activity (like Eclipse does for the template you described) or inside a Fragment, fortunately since Android 4.2 introduced Fragments inside other Fragments (this is also supported by the Android Compatibility Library for older version of Android).

The template generated by Eclipse is contained in an Activity (on tablets), or 2 Activities (for phones), because Eclipse doesn't know you need master/detail inside a fragment. So, you can't rely on Eclipse's template. But it's not that hard to just put 2 Fragments inside another Fragment.

You just need to forget about the ViewPager for a while and do your work inside the Fragment that will contain the Master/Detail Flow, let's call it MasterFragment.

  1. Declare 2 more Fragments: InnerListFragment, InnerDetailFragment. Also a InnerDetailActivity for phones.
  2. Declare 2 XML layout files for MasterFragment:

    • layout/fragment_master.xml - add inside this only the InnerListFragment <fragment> tag
    • layout-sw600dp/fragment_master.xml (for tablets >7") - add both InnerListFragment and InnerDetailFragment <fragment> tags.
  3. Now, I won't detail all your java code here, but inside MasterFragment.java, you need to check if the device is a tablet so that you know which of the 2 fragments are active on the screen.

    • if it's a phone, only InnerListFragment is visible. So just add the list and onClickListener will start InnerDetailActivity in which you need to put InnerDetailFragment.

    • if it's a tablet, both Inner fragments are visible. Don't start a new activity when clicking on a list item, just have a reference to both fragments inside MasterFragment so you can communicate between them.

That's the general idea. If you still have questions, do ask.

like image 145
Bogdan Zurac Avatar answered Nov 18 '22 01:11

Bogdan Zurac