TabLayout的滑动

(布局)

//先要把依赖写入

implementation 'com.android.support:design:27.1.1'

//布局可用线性布局就行




(Activity中)

// 创建标题集合
    channelBeanList = new ArrayList<>();
    //以键值对形式写入数据
    channelBeanList.add(new ChannelBean("Android", "https://gank.io/api/data/Android"));
    channelBeanList.add(new ChannelBean("iOS", "https://gank.io/api/data/iOS"));
    channelBeanList.add(new ChannelBean("all", "https://gank.io/api/data/all"));
    //设置适配器
    vp.setAdapter(new ChannelAdapter(getSupportFragmentManager()));
    tab_layout.setupWithViewPager(vp);
}
//设置内部类
private class ChannelAdapter extends FragmentPagerAdapter {
    public ChannelAdapter(FragmentManager fm) {
        super(fm);
    }
    @Override
    public Fragment getItem(int position) {
        return ChannelFragment.newInstance(channelBeanList.get(position).url);
    }
    @Override
    public int getCount() {
        return channelBeanList.size();
    }
    @Nullable
    @Override
    public CharSequence getPageTitle(int position) {
        return channelBeanList.get(position).title;
    }
}

(需要将viewpager实例到tablayout上)

//创建一个fragment包

//创建实例
public static Fragment newInstance(String url){
    ChannelFragment fragment = new ChannelFragment();
    Bundle ar = new Bundle();
    ar.putString("url",url);
    fragment.setArguments(ar);
    return fragment;
}

 

 

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