一 添加依赖包:
compile 'com.android.support:design:24.2.1'
二.写布局: activity_collect_product:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.design.widget.TabLayout
android:id="@+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabIndicatorColor="@color/red"
app:tabSelectedTextColor="@color/red"
app:tabTextColor="@color/black"/>
<!--可滑动的布局内容-->
<android.support.v4.view.ViewPager
android:id="@+id/vp_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
三.页面代码实现
public class CollectProductActivity extends BaseActivity {
private TabLayout mTabLayout;
private ViewPager mViewPager;
private String[] titles = {"页面1", "页面2"};
private List<Fragment> list;
@Override
public int getLayoutResId() {
return R.layout.activity_collect_product;
}
@Override
protected void initView() {
//实例化
mViewPager = (ViewPager) findViewById(R.id.vp_view);
mTabLayout = (TabLayout) findViewById(R.id.tabs);
}
@Override
protected void initListener() {
//页面,数据源
list = new ArrayList<>();
list.add(new Tab1Fragment());
list.add(new Tab2Fragment());
//ViewPager的适配器
MyAdapter adapter = new MyAdapter(getSupportFragmentManager());
mViewPager.setAdapter(adapter);
//绑定,会自动绑定
mTabLayout.setupWithViewPager(mViewPager);
}
@Override
protected void initData(boolean isNetWork) {
}
class MyAdapter extends FragmentPagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
return list.get(position);
}
@Override
public int getCount() {
return list.size();
}
//重写这个方法,将设置每个Tab的标题
@Override
public CharSequence getPageTitle(int position) {
return titles[position];
}
}
}
1.改变选中字体的颜色
app:tabSelectedTextColor="@android:color/holo_orange_light"
2.改变未选中字体的颜色
app:tabTextColor="@color/colorPrimary"
3.改变指示器下标的颜色
app:tabIndicatorColor="@android:color/holo_orange_light"
4.改变整个TabLayout的颜色
app:tabBackground="color"
5.设置文字大小
app:tabTextAppearance="@android:style/TextAppearance.Holo.Large"
//设置自定义table样子,有一个问题,会导致图片大小不受控制
for (int i = 0; i < adapter.getCount(); i++) {
TabLayout.Tab tab = mTabLayout.getTabAt(i);//获得每一个tab
tab.setCustomView(R.layout.tab_item);//给每一个tab设置view
TextView textView = (TextView) tab.getCustomView().findViewById(R.id.tab_text);
textView.setText(titlename[i]);//设置tab上的文字
}