将选择器定义为可绘制对象,并且还为选定/未选定状态提供可绘制对象。
对于这个解决方案,我从以下代码开始这个答案,然后添加了更改当前选项卡背景颜色的功能。
首先,选择器,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_unselected" android:state_selected="false" android:state_focused="false" android:state_pressed="false" />
</selector>
Then, tab_background_selected.xml
在可绘制文件夹中:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
<solid android:color="#d13fdd1a" />
</shape>
Then, tab_background_unselected.xml
在可绘制文件夹中:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
<solid android:color="#3F51B5" />
</shape>
最后,在你的styles.xml
,指定要使用的选择器,并指定选项卡指示符样式,因为app:tabIndicatorColor
TabLayout 中的属性现在将被忽略:
<style name="Base.Widget.Design.TabLayout" parent="android:Widget">
<item name="tabBackground">@drawable/tab_background</item>
<item name="tabIndicatorColor">#ff00ff</item>
<item name="tabIndicatorHeight">2dp</item>
</style>
上面示例颜色的结果:
附加说明:
使用 23.3.0 版本的支持库组件进行测试:
dependencies {
compile 'com.android.support:appcompat-v7:23.3.0'
compile 'com.android.support:cardview-v7:23.3.0'
compile 'com.android.support:recyclerview-v7:23.3.0'
compile 'com.android.support:design:23.3.0'
compile 'com.android.support:support-v4:23.3.0'
}