This question is similar to many other questions which describe the same problem I'm experiencing: I have a FragmentPagerAdapter with 5 items that doesn't display the Fragments after swiping to the third tab/swiping back. In my case however, my ViewPager isn't hosted in a Fragment, but directly in the activity, thus the getChildFragmentManager()
solution apparently doesn't apply here.
public class NotificationListActivity extends AppCompatActivity {
@BindView(R.id.container)
ViewPager mViewPager;
@BindView(R.id.tabs)
TabLayout tabLayout;
@BindView(R.id.toolbar)
Toolbar toolbar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notification_list);
ButterKnife.bind(this);
setSupportActionBar(toolbar);
mViewPager.setAdapter(new CategoryPagerAdapter(getSupportFragmentManager()));
tabLayout.setupWithViewPager(mViewPager);
}
...
public class CategoryPagerAdapter extends FragmentPagerAdapter {
@NonNull
private final String[] pageTitles;
@NonNull
private final Fragment[] fragments;
public CategoryPagerAdapter(@NonNull FragmentManager fm) {
super(fm);
this.pageTitles = // Intialization ommitted for brevity
this.fragments = // Initialization ommitted for brevity
}
@Override
public Fragment getItem(int position) {
if (position > fragments.length - 1)
throw new IllegalArgumentException("<ommitted>");
return fragments[position];
}
@Override
public int getCount() {
return pageTitles.length;
}
@Override
public CharSequence getPageTitle(int position) {
if (position > pageTitles.length - 1)
throw new IllegalArgumentException("<ommitted>");
return pageTitles[position];
}
I fixed the problem by increasing the OffscreenPageLimit:
mViewPager.setOffscreenPageLimit(5);
(I have 5 tabs)
This is not elegant, but fixes the problem for now. I'm not going to accept this as answer because it can't be the right way.