我使用来自com.android.support:design
库的新TabLayout
。我想要更改所选/未选选项卡的背景。
我查看了源代码,只发现tabBackground
属性可以更改所有标签的颜色,而无法控制所选标签的颜色。
如何控制所选/未选选项卡的背景?
我使用来自com.android.support:design
库的新TabLayout
。我想要更改所选/未选选项卡的背景。
我查看了源代码,只发现tabBackground
属性可以更改所有标签的颜色,而无法控制所选标签的颜色。
如何控制所选/未选选项卡的背景?
定义:
<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>
申请:
<android.support.design.widget.TabLayout
style="@style/AppTabLayout"
app:tabTextAppearance="@style/AppTabTextAppearance"
android:layout_width="match_parent"
.... />
TabLayout
中,选择的选项卡会用 tabIndicatorColor
指示。 - AkshayTabLayout
中,我们不能更改所选选项卡的背景吗? - Triet Doandrawable-selector
,其中包含两种状态:按下和未按下(或选中/未选中,我记不清了,你懂的)。然后将这个选择器设置为 tabBackground
。这样就可以控制所选选项卡的背景。 - IliaEremin如果您查看TabLayout.class
,您会注意到内部的TabView.class
用于标签的实际布局。它与任何其他布局相同,具有isSelected
属性。选择选项卡将对此产生影响,因此您所需做的就是创建选择器背景可绘制对象,如下所示:
<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>
并将它附加到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"/>
我阅读了如何在选定的选项卡上设置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"
/>
layout_height
和tabIndicatorHeight
具有相同的高度。因此,使用这种方式可以获得漂亮的过渡动画。我也遇到了这个问题。我在整个项目中搜索了tabIndicatorColor
,并在一些R.java
文件中找到了以下代码:
@see #TabLayout_tabBackground
@see #TabLayout_tabContentStart
@see #TabLayout_tabGravity
@see #TabLayout_tabIndicatorColor
@see #TabLayout_tabIndicatorHeight
@see #TabLayout_tabMaxWidth
@see #TabLayout_tabMinWidth
@see #TabLayout_tabMode
@see #TabLayout_tabPadding
@see #TabLayout_tabPaddingBottom
@see #TabLayout_tabPaddingEnd
@see #TabLayout_tabPaddingStart
@see #TabLayout_tabPaddingTop
@see #TabLayout_tabSelectedTextColor
@see #TabLayout_tabTextAppearance
@see #TabLayout_tabTextColor
所以问题已经解决了。希望这对你有所帮助。
例如,我使用IDEA
TabLayout
,而不是关于actionBar选项卡的。 - Guilherme Torres Castro