TabLayout选项卡样式

Ily*_*min 55 android android-design-library

TabLayoutcom.android.support:design库中使用new .我想更改所选/未选定选项卡的背景.我查看源代码,发现只有tabBackground属性可以更改所有选项卡的颜色,并且不会控制选定的选项卡颜色.

如何控制选定/未选择的标签背景?

Aks*_*hay 156

限定:

    <style name="AppTabLayout" parent="Widget.Design.TabLayout">
        <item name="tabMaxWidth">@dimen/tab_max_width</item>
        <item name="tabIndicatorColor">?attr/colorAccent</item>
        <item name="tabIndicatorHeight">4dp</item>
        <item name="tabPaddingStart">6dp</item>
        <item name="tabPaddingEnd">6dp</item>
        <item name="tabBackground">?attr/selectableItemBackground</item>
        <item name="tabTextAppearance">@style/AppTabTextAppearance</item>
        <item name="tabSelectedTextColor">@color/range</item>
    </style>

    <!-- for text -->
    <style name="AppTabTextAppearance" parent="TextAppearance.Design.Tab">
        <item name="android:textSize">12sp</item>
        <item name="android:textColor">@color/orange</item>
        <item name="textAllCaps">false</item>
    </style>
Run Code Online (Sandbox Code Playgroud)

应用:

<android.support.design.widget.TabLayout
    style="@style/AppTabLayout"
    app:tabTextAppearance="@style/AppTabTextAppearance"
    android:layout_width="match_parent"
    .... />
Run Code Online (Sandbox Code Playgroud)


Mic*_*hal 16

如果你看一下TabLayout.class你会发现内部TabView.class标签的实际布局.它与任何其他isSelected属性的布局相同.选择选项卡也会对此产生影响所以您需要做的就是创建选择器背景drawable

<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_selected="true" android:drawable="@color/tab_bg_selected"/>
<item android:drawable="@color/tab_bg_unselected"/></selector>
Run Code Online (Sandbox Code Playgroud)

并将其附加到tabBackground属性,例如XML

<android.support.design.widget.TabLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:tabBackground="@drawable/tab_bg"
            app:tabIndicatorHeight="4dp"/>
Run Code Online (Sandbox Code Playgroud)


Ily*_*min 8

我阅读了如何设置ActionBar样式,选中选项卡上的选项卡背景,并找出要做的事情.这是非常类似的问题,但我发现了一个很棒的解决方案专门用于TabLayout:

<android.support.design.widget.TabLayout
    android:id="@+id/tabs"
    android:layout_width="match_parent"
    android:layout_height="48dp"
    android:background="@color/tab_layout_color"
    app:tabIndicatorHeight="48dp"
    app:tabIndicatorColor="@color/selected_tab_color"
    />
Run Code Online (Sandbox Code Playgroud)

请注意layout_heighttabIndicatorHeight具有相同的高度.所以你用这种方式得到漂亮的过渡动画.