private void setupViewPager(ViewPager viewPager) { Adapter adapter = new Adapter(getSupportFragmentManager()); adapter.addFragment(new CheeseListFragment(), "Tab 1"); adapter.addFragment(new CheeseListFragment(), "Tab 2"); adapter.addFragment(new CheeseListFragment(), "Tab 1"); adapter.addFragment(new CheeseListFragment(), "Tab 2"); viewPager.setAdapter(adapter); } static class Adapter extends FragmentPagerAdapter { private final List<Fragment> mFragments = new ArrayList<Fragment>(); private final List<String> mFragmentTitles = new ArrayList<String>(); public Adapter(FragmentManager fm) { super(fm); } public void addFragment(Fragment fragment, String title) { mFragments.add(fragment); mFragmentTitles.add(title); } @Override public Fragment getItem(int position) { return mFragments.get(position); } @Override public int getCount() { return mFragments.size(); } @Override public CharSequence getPageTitle(int position) { return mFragmentTitles.get(position); } } 

This method is called, for some reason only two times. It's not entirely clear why.

CheeseListFragment.java

  public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { RecyclerView rv = (RecyclerView) inflater.inflate( R.layout.fragment_cheese_list, container, false); // setupRecyclerView(rv); return rv; } 

    1 answer 1

    Apparently you expect that all the fragments (in your example 4) will be created immediately?

    If so, then you did not understand that ViewPager creates only those fragments, which now displays + those to the left and to the right of the displayed one. Because By default, the first fragment is displayed, then only he and the next one are created accordingly. From here and operation of methods of life cycle only 2 fragments from 4.

    • How everything turns out to be simple) - Rajab
    • one
      You can also change this behavior using the setOffscreenPageLimit method - Mikhail
    • @ ЮрийСПБ How can I get access to the fragment that hangs in my memory, that is, the one that is next? My values ​​are set in onCreateView , and due to the fact that the fragment has already been created and stored in memory, its onCreateView method onCreateView not work. - McDaggen
    • @McDaggen, this is a very difficult question. Describe what how and why - a few pages of small text. Briefly - you can try to keep links to fragments in the ViewPager adapter. - Yuriy SPb
    • @YuriySPb And if you do not get access, and for example, update it in the same memory? For example, I make changes in the current snippet, and I need the next one to be updated in memory too - McDaggen