TabLayout,ViewPager,Fragment结合使用

在xml文件中,书写TabLayout和ViewPager标签

    
    

    
    
    

ViewPager的适配器

/**
     * 首页frag布局的适配器,
     */
    class MyHomeVpContentAdapter extends FragmentStatePagerAdapter {

        public MyHomeVpContentAdapter(FragmentManager fm) {
            super(fm);
        }
//          用来设置tablayout的标签名
        @Override
        public CharSequence getPageTitle(int position) {
            return tabs[position];
        }

        @Override
        public Fragment getItem(int position) {
            switch (position) {
                case HOME_POS:
                    return mHomeTabFragment;
                case LIVE_POS:
                    return mLiveFragment;
                case FOLLOW_POS:
                    return mFollowFragment;
                case OTHER_POS:
                    return mOtherFragment;
            }
            throw new IllegalStateException("No fragment at position " + position);
        }

        @Override
        public int getCount() {
            return tabs.length;
        }
    }

//         viewpager 和 tablayout的结合
        //初始化 viewpager的 adapter
        MyHomeVpContentAdapter myHomeVpContentAdapter = new MyHomeVpContentAdapter(getFragmentManager());
        //设置为加载一个
        viewpager.setOffscreenPageLimit(1);
        viewpager.setAdapter(myHomeVpContentAdapter);
        //tablayout 绑定 viewpager
        tablayout.setupWithViewPager(viewpager);
        

新建Fragment

参考我的另一篇博客.
Activity,Fragment的基类封装,简化findViewById,Fragment懒加载和不重复加载等

你可能感兴趣的:(TabLayout,ViewPager,Fragment结合使用)