如何在单击时更改选项卡的背景颜色

时间:2016-03-13 04:03:00

标签: android android-tablayout

我有TabLayout,它显示大约4个标签。当我点击一个标签时,背景颜色是一个令人作呕的黄色突出显示(然后当我发布时恢复正常)。如何在转换到所需片段期间将其更改为白色。

这是我的应用主题

app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"

这是TablayoutViewPager

<android.support.design.widget.TabLayout
    android:id="@+id/sliding_tabs"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/headBlue"
    app:tabMaxWidth="0dp"
    app:tabGravity="fill"
    app:tabIndicatorColor="@android:color/white"
    app:tabMode="fixed" />

<android.support.v4.view.ViewPager
    android:id="@+id/viewpager"
    android:layout_width="match_parent"
    android:layout_height="0px"
    android:layout_weight="1" />

以下是依赖项

compile 'com.android.support:appcompat-v7:23.2.0'
compile 'com.android.support:design:23.2.0'

1 个答案:

答案 0 :(得分:0)

第1步

在drawable目录中为名为 tab_selector.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>

第2步

在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="#FF0000" />
</shape>

第3步

在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="#00FF00" />
</shape>

第4步

最后,将此应用于您的风格。

<style name="Base.Widget.Design.TabLayout" parent="android:Widget">
    <item name="tabBackground">@drawable/tab_selector</item>
</style>