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 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
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:)
OnPageChangeListener is the correct way to go, but you will need to refactor your adapter a bit in order to keep a reference to each Fragment contained in the FragmentPagerAdapter. Then, instead of creating a new Fragment, use the one contained in the adapter: mViewPager. addOnPageChangeListener(new ViewPager.
You'll just need to cast it to the real fragment class if you want to call a specific method. int pos = viewpager. getCurrentItem(); Fragment activeFragment = adapter. getItem(pos); if(pos == 0) ((NPListFragment)activeFragment).
This method is deprecated.
The updateFragmetData method will be called in the current selected viewpager item fragment. You can also add a tag parameter to updateFragmetData so that you can be sure the right fragment instance is called. If required you can call isVisible in updateFragmetData implementation to make sure the fragment is visible.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With