TabLayout+ViewPager滑动

主布局



    
        
        
            
        
    
    
    

public class ForumActivityPresenter extends AppDelegate{

    private ViewPager hot_ViewPager;
    private TabLayout tab_layout;

    @Override
    public int getLayoutId() {
        return R.layout.activity_forum;
    }

    @Override
    public void initData() {
        super.initData();
        hot_ViewPager = get(R.id.hot_ViewPager);
        tab_layout = get(R.id.tab_layout);
        //V适配器
        MyPagerAdapter myPagerAdapter = new MyPagerAdapter(((ForumActivity)context).getSupportFragmentManager());
        //添加fragment
        ArrayList fragments = new ArrayList<>();
        fragments.add(new Fragment01());
        fragments.add(new Fragment02());
        fragments.add(new Fragment03());
        myPagerAdapter.setFragments(fragments);

        //添加头
        ArrayList titles = new ArrayList<>();
        titles.add("全部帖子");
        titles.add("热门帖子");
        titles.add("精华帖子");
        myPagerAdapter.setTitles(titles);
        //设置tablayout的模式
        tab_layout.setTabMode(TabLayout.MODE_FIXED);
        hot_ViewPager.setAdapter(myPagerAdapter);
        //关联viewpager
        tab_layout.setupWithViewPager(hot_ViewPager);
    }

    private Context context;
    @Override
    public void getContext(Context context) {
        super.getContext(context);
        this.context = context;
    }
}

适配器

public class MyPagerAdapter extends FragmentPagerAdapter{
    ArrayList fragments;
    ArrayList titles;

    public MyPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    public void setFragments(ArrayList fragments) {
        this.fragments = fragments;
    }

    public void setTitles(ArrayList titles) {
        this.titles = titles;
    }

    @Override
    public Fragment getItem(int position) {
        return fragments.get(position);
    }

    @Override
    public int getCount() {
        return fragments.size();
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return titles.get(position);
    }
}

 

你可能感兴趣的:(TabLayout+ViewPager滑动)