1. 程式人生 > >更改TabLayout選中的背景色

更改TabLayout選中的背景色

專案中有這種需求,google了下發現瞭解決方案,摘錄如下方便大家排查.
原文連結

原理是利用selector

第一步
在drawable資料夾下建立檔案 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>

第二步
在drawable資料夾下建立選中效果的檔案 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>

第三步
在drawable資料夾下建立未選中效果的檔案 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>

最後
建立一個style

<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>

重點使用該屬性<item name="tabBackground">@drawable/tab_background</item>

效果圖