2

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.

My Activity

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);
    }
    ...

My Adapter

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];
    }
comrade
  • 4,590
  • 5
  • 33
  • 48
looper
  • 1,929
  • 23
  • 42

1 Answers1

0

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.

looper
  • 1,929
  • 23
  • 42
  • I wanted to chime in since this fixed my problem. Per comments on the viewpager we have: **Set the number of pages that should be retained to either side of the CURRENT page** so if you have 5 pages, setting it to 4 would have worked and since it is recommend to use the minimum I woud advised to do so. – Beto Apr 12 '18 at 22:09