Android TabLayout custom indicator width

Goltsev Eugene picture Goltsev Eugene · Aug 16, 2017 · Viewed 14.7k times · Source

I want to reduce width of indicator - for example, make it's width not whole tab width, but 1/2 of tab width.
That's all I need to do, so I don't want to download some custom library and search where I can do this.

Is it a way to do this or I should write such view by myself?

Answer

Mavamaarten picture Mavamaarten · Nov 13, 2019

if a tab indicator with a fixed size is what you want, to achieve you can create an indicator shape with a fixed size by drawable:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:gravity="center">
        <shape android:shape="rectangle">
            <solid android:color="@color/colorAccent" />
            <corners
                android:topLeftRadius="2dp"
                android:topRightRadius="2dp" />
            <size
                android:width="16dp"
                android:height="2dp" />
        </shape>
    </item>
</layer-list>

Then on the TabLayout, you can then just set the tab indicator drawable. at the same time, you also have to set the tabIndicatorColor

 app:tabIndicatorColor="@color/tabIndicatorColor"
 app:tabIndicator="@drawable/tab_indicator"

Because the drawable itself center the shape inside its bounds, the indicator will have a fixed size.

if you want the indicator to match the width of the label, you can remove the tabIndicator android:gravity.

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="rectangle">
            <solid android:color="@color/colorAccent" />
            <corners
                radius="2dp" />
            <size
                android:width="16dp"
                android:height="2dp" />
        </shape>
    </item>
</layer-list>