如何在制表布局的非活动选项卡上设置特定颜色的下划线?我的自定义视图占用最大标签宽度



我无法处理在TabLayout选项卡上设置自定义视图。我想设置下划线(就像在活动选项卡上的指示器)与每个非活动选项卡上的特定颜色。我是这样创建视图的:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:background="@color/colorPrimary">
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="@style/tab_layout_item"
    android:layout_centerInParent="true"
    tools:text="All in"/>
<View
    android:layout_width="wrap_content"
    android:layout_height="7dp"
    android:background="@color/colorPrimaryDark"
    android:layout_alignParentBottom="true"/>

但是wrap_content参数不起作用并且视图占用了最大制表符宽度。

这是我的TabLayout xml:

        <android.support.design.widget.TabLayout
        android:layout_width="match_parent"
        android:layout_height="48dp"
        android:background="@color/background_primary"
        app:tabIndicatorHeight="0dp"
        app:tabMode="scrollable"
        app:tabGravity="fill"
        app:tabPaddingBottom="0dp"
        app:tabPaddingTop="0dp"
        app:tabPaddingStart="0dp"
        app:tabPaddingEnd="0dp"
        android:layout_gravity="bottom"/>

如何为TabLayout选项卡创建适合文本的自定义视图(特别是当字符串内部很短时)?

也许是一个更好的方法来实现这个结果?

填充标签:

LayoutInflater inflater = getActivity().getLayoutInflater();
RelativeLayout tab1 = (RelativeLayout) inflater.inflate(R.layout.component_custom_tab,null);
RelativeLayout tab2 ...

为分隔符添加id:

<View
    android:id="@+id/divider"
    android:layout_width="wrap_content"
    android:layout_height="7dp"
    android:background="@color/colorPrimaryDark"
    android:layout_alignParentBottom="true"/>

设置每个标签的颜色:

tab1.findViewById(R.id.divider).setBackgroundColor(getColor(R.color.color_1));
tab2 ....

在TabLayout中添加标签:

mTabLayout.addTab(mTabLayout.newTab().setCustomView(tab1), index1);
mTabLayout.addTab(mTabLayout.newTab().setCustomView(tab2), index2);
...

最新更新