I have a ViewPager
with three Fragments
, each one shows a List
(or Grid
).
In the new Android API level 17
(Jelly Bean 4.2), one of the features is Nested Fragments. The new functionality description says:
if you use ViewPager to create fragments that swipe left and right and consume a majority of the screen space, you can now insert fragments into each fragment page.
So, if I understand right, now I can create a ViewPager
with Fragments
(with a button inside for example) inside, and when user press the button show another Fragment
without loose the ViewPager
using this new feature.
I've expended my morning trying to implement this several different ways, but I can´t get it working... Can somebody add a simple example of how to implement this?
PS: I'm only interested in doing at this way, with getChildFragmentManager
to learn how works.
Edit: If you want to replace all the content of a page in a
ViewPager
you could still use nested fragments, but some changes are needed. Check the sample below(theFragmentActivity
, setting theViewPager
and thePagerAdapter
are the same as the previous snippet of code):At a quick look it works, but issues may appear as I haven't tested it to much.
Using nested fragments seems pretty easy, until Commonsware comes with a more elaborated sample you can try the code below:
I was lazy and made everything in code but I'm sure it can work with inflated xml layouts.
I have created a ViewPager with 3 elements and 2 sub elements for index 2 and 3 and here what I wanted to do..
I have implemented this with the help from previous questions and answers from StackOverFlow and here is the link.
ViewPagerChildFragments
Assuming you have created the correct xml layouts. It is now very simple to display fragments in a ViewPager that is hosted by another Fragment.
The code looks something like this in a parent Fragment:
It is important to use Fragment.getChildFragmentManager() when instantiating the FragmentPagerAdapter. Also note that you cannot use Fragment.setRetainInstance() on the children fragments or you'll get an exception.
Source code can be found at: https://github.com/marcoRS/nested-fragments