OnCreateView for the tab called when you select the adjacent tab?

advertisements

I am having a weird issue where onCreateView is being called every time I navigate to an adjacent tab in my TabLayout. Here is my code:

news_feed.java:

private static TabLayout tabLayout;

@Override
public void onCreate(Bundle savedInstanceState) {
    tabLayout = (TabLayout) findViewById(R.id.tab_layout);
    tabLayout.addTab(tabLayout.newTab().setText("Public"));
    tabLayout.addTab(tabLayout.newTab().setText("Friends"));
    tabLayout.addTab(tabLayout.newTab().setText("My Tabs"));
    tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);

    final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
    final PagerAdapter adapter = new PagerAdapter
            (getSupportFragmentManager(), tabLayout.getTabCount());
    viewPager.setAdapter(adapter);
    viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
    tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            viewPager.setCurrentItem(tab.getPosition());
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {

        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {

        }
    });
}

PublicTab.java:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    System.out.println("Creating a new view");
    fragmentView = inflater.inflate(R.layout.public_tab, container, false);
    progressOverlay = fragmentView.findViewById(R.id.progress_overlay);
    AndroidUtils.animateView(progressOverlay, View.VISIBLE, 0.9f, 200);
    getPublicPosts(progressOverlay, fragmentView);
    return fragmentView;
}

I have 3 other tabs that look exactly like PublicTab.java but with different layouts. I am not sure why onCreateView is being called so frequently. I thought in the lifecycle, onCreateView is only invoked for 2 reasons: 1. when we first initialize the tabs 2. if we come out from onStop or onPause method.

However, when switching between the tabs that are next to the actual tab, the println message is called like above and this is not what I want because I don't want to update the View of that fragment so frequently: only during the first 2 reasons above. Anyone know why this is happening? Any help would be appreciated! Thanks!


Use setoffScreenPageLimit Android documentation:

public void setOffscreenPageLimit (int limit)

Set the number of pages that should be retained to either side of the current page in the view hierarchy in an idle state. Pages beyond this limit will be recreated from the adapter when needed

The default value is set to 1.