参考连接为:https://www.2cto.com/kf/201802/719334.html
参考连接二为:https://www.jianshu.com/p/d86e31dcc97b
在项目开发中很多场景都会碰到tab栏切换的效果,实现的思路也有很多种,tabhost+fragment,radionbtton+viewpager等方式都可以实现,这里就说下tablayout+viewpager的实现方式;tablayout是android5.0推出来的一个MaterialDesign风格的控件,是专门用来实现tab栏效果的;功能强大,使用方便灵活;
1、引入依赖库
compile 'com.android.support:design:25.3.1'
compile 'com.android.support:support-v4:25.3.1'
- 1
- 2
2、xml布局文件中使用
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.mdtablayout.MainActivity">
<android.support.design.widget.TabLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabIndicatorColor="@color/colorAccent"
app:tabTextColor="@android:color/black"
app:tabSelectedTextColor="@color/colorAccent"
app:tabMode="scrollable"
app:tabGravity="fill"/>
<android.support.v4.view.ViewPager
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
tablayout提供了很多的属性可以设置:
app:tabIndicatorColor 指示器颜色
app:tabTextColor tab栏字体颜色
app:tabSelectedTextColor tab栏字体被选颜色
app:tabIndicatorHeight 指示器高度
app:tabBackground tab背景颜色
app:tabMaxWidth tab栏最大宽度
app:tabTextAppearance tab栏字体样式
app:tabMinWidth tab栏最小宽度
......
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
这些属性可以下xml中设置,也可以使用代码进行设置;需要注意这两个属性:
app:tabMode="";有scrollable和fixed两个属性值
scrollable:可滑动;
fixed:不能滑动,平分tabLayout宽度;
app:tabGravity="";有center和fill两个属性值
fill:tabs平均填充整个宽度;
center:tab居中显示;
- 1
- 2
- 3
- 4
- 5
- 6
- 7
3、设置tablayout和viewpager,并将tablayout和viewpager进行关联
在设置tablayout和viewpager,并将tablayout和viewpager进行关联有两中方式可以实现:
方式一:
3.1、TabLayout和Viewpager关联
tablayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
//tab被选的时候回调
viewpager.setCurrentItem(tab.getPosition(),true);
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
//tab未被选择的时候回调
}