1、需要在build中添加引用的包
compile 'com.android.support:design:25.2.0'
2、布局:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/background2"
android:orientation="vertical">
<android.support.design.widget.TabLayout
android:id="@+id/tabs"
style="@style/TabLayoutStyle"
android:layout_width="match_parent"
android:layout_height="@dimen/dp_50"
android:layout_marginTop="@dimen/dp_6" />
<android.support.v4.view.ViewPager
android:id="@+id/vp_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="@dimen/dp_6" />
</LinearLayout>
注意:在xml中tabs的宽度如果是wrap_content,则会根据文本大小显示多宽
在xml中tabs的宽度如果是match_parent,则会根据个数平分屏幕的宽度
特别注意:
要使用TabLayout,Activity主题必须为Theme.AppCompat类型的主题,如:Theme.AppCompat.Light.NoActionBar
改变选中的背景色和文字大小(如下介绍)
3、代码实现:
主要是viewpager和TabLayout的初始化及绑定,TabLayout的事件处理
mViewPagerTab = (ViewPager) findViewById(R.id.vp_view);
mTabLayout = (TabLayout) findViewById(R.id.tabs);
4、修改TabLayout的文字大小:
<style name="TabLayoutTextAppearance" parent="TextAppearance.AppCompat.Widget.ActionBar.Title">
<item name="android:textSize">@dimen/sp_20</item>
</style>
必须这样,否则没有效果
5、修改TabLayout的Item背景色
<!--tab-->
<style name="TabLayoutStyle" parent="android:Widget">
<item name="tabBackground">@drawable/tab_backgroud</item>
<item name="tabIndicatorColor">@color/transparent_color</item>
<item name="tabIndicatorHeight">@dimen/dp_0</item>
<item name="tabSelectedTextColor">@color/text_color</item>
<item name="tabTextColor">@color/tab_text_default_color</item>
<item name="tabTextAppearance">@style/TabLayoutTextAppearance</item>
</style>
如果4 问题不那样写,而在5中写是没有效果的
6、选择器的样式
(1)tab_background.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/tab_background_selected"
android:state_selected="true" />
<item android:drawable="@drawable/tab_background_default"
android:state_focused="false"
android:state_pressed="false"
android:state_selected="false" />
</selector>
(2)tab_backgroud_selsected.xml
注意:一定要注意:根是shape--------在没有在意跟的时候,默认是selector,这个选择器是不好用的,坑了我好久。。。
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<!--填充色-->
<solid android:color="@color/tab_selected_color" />
<!-- 线的宽度,颜色灰色 -->
<stroke
android:width="@dimen/dp_0.5"
android:color="@color/background2"></stroke>
<!-- 矩形的圆角半径 -->
<corners android:radius="@dimen/dp_10" />
</shape>
(3)tab_backgroud_default.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="@color/background2" />
</shape>
有的是在(1)中选择的时候是color="直接颜色值",当时drawable的时候一定注意根是shape