1

Replacing Fragments in ViewPager is a question that has been asked many times but most answers are hacks, broken/not complete or quite old. This example is working really well - https://github.com/danilao/fragments-viewpager-example but it actually uses an empty root fragment and adds the real fragment on createView.

Is there any other better way to avoid having to use a root frame?

Krishnaraj
  • 2,360
  • 1
  • 32
  • 55

2 Answers2

2

The correct approach would be to override your PagerAdapter's getItemPosition() to update your PagerAdapter with the new Fragment:

Called when the host view is attempting to determine if an item's position has changed. Returns POSITION_UNCHANGED if the position of the given item has not changed or POSITION_NONE if the item is no longer present in the adapter.

The default implementation assumes that items will never change position and always returns POSITION_UNCHANGED.

In this case, pages that haven't changed return PagerAdapter.POSITION_UNCHANGED, the Fragment that is removed returns PagerAdapter.POSITION_NONE, and the new Fragment gets its new position.

You'll change the underlying data in your PagerAdapter, then call notifyDataSetChanged(). This is what triggers the ViewPager to call getItemPosition() for each visible Fragment, replacing or moving them as needed.

Community
  • 1
  • 1
ianhanniballake
  • 191,609
  • 30
  • 470
  • 443
  • The small problem with this technique is that if you want to completely replace Fragment A with Fragment B in a `FragmentPagerAdapter` for example, Fragment A is simply detached but not destroyed, so it's still around even if you want to get rid of it. Do you have a workaround for this ? – BladeCoder Aug 02 '15 at 20:03
  • @BladeCoder - switching over to `FragmentStatePagerAdapter` is certainly one way. Providing deep or persistent tabs is a [navigation anti-pattern](https://www.youtube.com/watch?v=Sww4omntVjs&feature=youtu.be&t=539) that should be avoided anyways. – ianhanniballake Aug 02 '15 at 21:30
  • Can't agree more about deep and persistent tabs, that's why I've always disliked the Instagram app. I developed an app where the user may choose in the options if he wants fragment A or fragment B to represent the content of a tab, and I opted for the child fragment option to allow switching the display on-the-fly. I believe that approach is acceptable in that case. – BladeCoder Aug 02 '15 at 22:14
  • Thanks for clearing my doubt. For those looking for a complete example, check http://stackoverflow.com/a/18612049/206292 – Krishnaraj Aug 04 '15 at 07:07
0

Your example uses the right technique (child fragments inside root fragment) but the wrong way: for managing child fragments inside the root fragment, it must use the child fragment manager using getChildFragmentManager().

BladeCoder
  • 12,779
  • 3
  • 59
  • 51