How to replace Fragment inside ViewPager, using PagerAdapter?

AlexMomotov picture AlexMomotov · Sep 11, 2013 · Viewed 9.3k times · Source

My problem

I am using a ViewPager to display fragments inside a FragmentActivity. ViewPager gets fragments from the attached FragmentPagerAdapter.

mViewPager = (ViewPager) findViewById(R.id.view_pager);       
mAdapter = new HomePagerAdapter(getSupportFragmentManager());    
mViewPager.setAdapter(mAdapter);

Suppose ViewPager has 3 fragments to display: Fragment1, Fragment2, Fragment3. Fragment1 is a grid fragment and displays a grid. Fragment2 and Fragment3 have their own content to display. When the use swipes on the screen, ViewPager will display the next fragment - Fragment2. And so on.

What I want?

What I want is that, when an item from the grid (displayed by Fragment1) is clicked, Fragment1 should be completely replaced with some other fragment, say Fragment4 (this is different fragment and is not returned by the attached adapter). User will work on Fragment4 and after ButtonBack click (just button iside Fragment4), Fragment1 with the grid should be displayed again. Meanwhile ViewPager should behave the same i.e on swipe, the next fragment (in our case Fragment2) will be displayed.

So I just want to get the same behavior as in example: http://developer.android.com/training/basics/fragments/fragment-ui.html#Replace

My question

So, is this possible to achieve? If yes, then how to? I would greatly appreciate for your help. Alex. P.S. Sorry for my English:)

Answer

dlao picture dlao · Jan 30, 2014

I've made a little example that shows how to achieve it:

https://github.com/danilao/fragments-viewpager-example

I think the point is to use another fragment as a container.