ViewPager setOffscreenPageLimit not working when using it as NestedFragment with getChildFragmentManager

二次信任 提交于 2019-12-06 05:07:15

I ran into the same problem. This is how I do and this is working for me, it has the same architetcure as what you expect to have.

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onSaveInstanceState(savedInstanceState);
        view = inflater.inflate(R.layout.communitylayout, container, false);
        Bundle data = getArguments();

        TabLayout tabLayout = (TabLayout) view.findViewById(R.id.comtabs);
        tabLayout.setTabMode(TabLayout.MODE_FIXED);


        // add tabs
        tabLayout.addTab(tabLayout.newTab());
        tabLayout.addTab(tabLayout.newTab());
        tabLayout.addTab(tabLayout.newTab());

        RelativeLayout layout1 = (RelativeLayout) inflater.inflate(R.layout.communitytablayoutleft, container, false);
        RelativeLayout layout2 = (RelativeLayout) inflater.inflate(R.layout.communitytablayout, container, false);
        RelativeLayout layout3 = (RelativeLayout) inflater.inflate(R.layout.communitytablayoutright, container, false);
        tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);



        pager = (ViewPager) view.findViewById(R.id.compager);
        CommunityPagerFragment adapter = new CommunityPagerFragment(getChildFragmentManager());

        pager.setAdapter(adapter);
        tabLayout.setupWithViewPager(pager);
        pager.setCurrentItem(0);
        tabLayout.setOnTabSelectedListener(this);

        // KEEP FRAGMENT STATE INSIDE OF THE TAB
        pager.setOffscreenPageLimit(2);


        ((TextView)layout1.findViewById(R.id.tabtext)).setText(tabs[0]);
        ((TextView)layout2.findViewById(R.id.tabtext)).setText(tabs[1]);
        ((TextView)layout3.findViewById(R.id.tabtext)).setText(tabs[2]);

        //tabLayout.set


        tabLayout.getTabAt(0).setCustomView(layout1);
        tabLayout.getTabAt(1).setCustomView(layout2);
        tabLayout.getTabAt(2).setCustomView(layout3);

        onTabSelected(tabLayout.getTabAt(1));
        //tabLayout.set

        return view;

And if you want to get the Tabs working by click in addition of the swipe, add the following:

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

    pager.setCurrentItem(tab.getPosition());

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!