1:基本设置
val tabTitles =arrayOf("最近七天收益","下属会员充值","历史收益") //TabLayout的三个item
val list: MutableList = ArrayList() //放置子view的集合
val incomeFragment = IncomeFragment() //子view1
val myMemberRechargeFragment = MyMemberRechargeFragment() //子view2
val incomeHistoryFragment = IncomeHistoryFragment() //子view3
list.add(incomeFragment) //添加子view1
list.add(myMemberRechargeFragment) //添加子view2
list.add(incomeHistoryFragment) //添加子view3
val adapter = MyViewPageAdapter(supportFragmentManager, list, tabTitles) //设置adapter
content.setAdapter(adapter) //设置adapter,content为ViewPager的id
tab.setupWithViewPager(content) //设置Tab Layout与ViewPager联动
tab.setTabMode(TabLayout.MODE_FIXED) //设置模式
2:adapter(MyViewPageAdapter)
public class MyViewPageAdapterextends FragmentPagerAdapter {
private List list;
private String tabTitles[];
public MyViewPageAdapter(FragmentManager fm, List list,String tabTitles[]) {
super(fm);
this.list = list;
this.tabTitles = tabTitles;
}
@Override
public Fragment getItem(int i) {
return list.get(i);
}
@Override
public int getCount() {
return list.size();
}
@Override
public CharSequence getPageTitle(int position) {
return tabTitles[position];
}
@Override
public void destroyItem(ViewGroup container,int position, Object object) {
//super.destroyItem(container, position, object); 避免多出销毁Fragment
}
}
3:设置TabLayout默认选中
content.setCurrentItem(type) //content为ViewPager的id,type为需要选中的item
tab.getTabAt(type)!!.select() //tab为TabLayout的id,type同上。