Tablayout+Viewpager+fragment实现联动效果

当前该类是viewpager和fragment的适配器
public class MyViewPagerAdapter extends FragmentPagerAdapter {
  //显示页卡标题的集合
 private List titleList;
   //viewpager上承载展示数据的fragmenet集合
 private List fragmentList;
    public MyViewPagerAdapter(FragmentManager fm, List titleList, List fragmentList) {
        super(fm);
        this.titleList = titleList;
        this.fragmentList = fragmentList;
    }
//fragment的条目数
    @Override
    public Fragment getItem(int position) {
        return fragmentList.get(position);
    }
//fragment的个数
    @Override
    public int getCount() {
        return fragmentList.size();
    }
//获取页卡标题内容
    @Override
    public CharSequence getPageTitle(int position) {
        return titleList.get(position);
    }
}

该类是引用viewpager和tablayout的类

public class MainActivity extends AppCompatActivity {
 
//viewpager上承载展示数据的fragmenet集合
private List fragmentList;
//显示页卡标题的集合
private List titleList; private ViewPager vp; private TabLayout tab; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate( savedInstanceState); setContentView(R.layout. activity_main);

 initView(); initData(); } private void initData() {
//初始化集合数据
  fragmentList = new ArrayList<>(); titleList = new ArrayList<>(); String[] str = { " 周一 ", " 周二 ", " 周三 ", " 周四 ", " 周五 ", " 昨天 ", " 今天 "}; for ( int i = 0; i < 6 ; i++) { titleList.add(str[i]); } for ( int i = 0; i < titleList.size() ; i++) { //添加fragment到集合中
MyFragment myFragment = new MyFragment(); fragmentList.add(myFragment); }
//设置适配器
  vp.setAdapter( new MyViewPagerAdapter(getSupportFragmentManager(), titleList, fragmentList));
//viewpager和tablayout建立关联
  tab.setupWithViewPager( vp); } private void initView() { vp = (ViewPager) findViewById(R.id. vp); tab = (TabLayout) findViewById(R.id. tab); }}

布局文件

注意:导入 compile 'com.android.support:design:24.2.1'依赖包

        android:id="@+id/tabhot"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:tabIndicatorColor="@color/colorYellow"
        app:tabSelectedTextColor="@color/colorZong"
        app:tabTextColor="@color/colorBlack"/>
     
              android:id="@+id/hot_vp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

你可能感兴趣的:(Tablayout+Viewpager+fragment实现联动效果)