1:TabLayout 的简单使用
1;在布局文件中申明,并在TabLayout下面放ViewPager
<android.support.design.widget.TabLayout
android:id="@+id/Tablayout1"
app:tabMode="scrollable"
app:tabSelectedTextColor="@color/colorPrimary"
app:tabIndicatorColor="@color/colorPrimary"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
<android.support.v4.view.ViewPager
android:id="@+id/vp_main"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight = "1"
/>
2:在JAVA文件中找出控件
mTablayout = (TabLayout) findViewById(R.id.Tablayout1);
mVp_main = (ViewPager) findViewById(R.id.vp_main);
3:为ViewPager设置适配器,适配器应该继承FragmentPagerAdapter,大致和普通的ViewPager 适配器差不多,多了最后一个方法,每个ViewPager 页面返回的都是一个Fragment对象。
public class MainTabAdapter extends FragmentPagerAdapter {
private List<FirstPagerFragment> mList_fragment ;
private String[] mList_titlt;
public MainTabAdapter(FragmentManager fm,List<FirstPagerFragment> List_fragment,String[] List_titlt) {
super(fm);
mList_fragment = List_fragment ;
mList_titlt = List_titlt;
}
@Override
public FirstPagerFragment getItem(int position) {
return mList_fragment.get(position);
}
@Override
public int getCount() {
return mList_fragment.size();
}
/*
* 这个是设置页签标题*/
@Override
public CharSequence getPageTitle(int position) {
return mList_titlt[position] ;
}
}
4:设置适配器后将TabLayout和ViewPager绑定起来
//为ViewPager设置适配器
mVp_main.setAdapter(mTabAdapter);
//将TabLayout 和ViewPager 绑定起来
mTablayout.setupWithViewPager(mVp_main);