Search code examples
androidxmlandroid-tablayouttabbar

Adding a line below TabLayout


I'm having a trouble trying to add a line below the TabLayout, but it has to be behind the selector line. Should be something like this:

Exemple

I already tried to add a custom view, but each tab have some margin inside, so didn't worked out.

any ideas?

This is what I got right now:

current_tablayout

Here its how i'm adding it on XML:

<android.support.design.widget.TabLayout
    android:id="@+id/tabs"
    android:layout_width="match_parent"
    android:layout_height="60dp"
    app:tabBackground="@color/white"
    app:tabIndicatorColor="@color/colorAccent"
    app:tabTextColor="@color/white"/>

and this is what i'm doing via code:

private void configureTabLayout() {
    TabLayout.Tab tabHome = mTabLayout.newTab().setIcon(R.drawable.ic_home_cinza);
    TabLayout.Tab tabEmprestimos = mTabLayout.newTab().setIcon(R.drawable.ic_emprestimos_cinza);
    TabLayout.Tab tabPersonal = mTabLayout.newTab().setIcon(R.drawable.ic_usuario_cinza);

    View root = mTabLayout.getChildAt(0);
    if (root instanceof LinearLayout) {
        ((LinearLayout) root).setShowDividers(LinearLayout.SHOW_DIVIDER_MIDDLE);
        GradientDrawable drawable = new GradientDrawable();
        drawable.setColor(getResources().getColor(R.color.silver));
        drawable.setSize(2, 1);
        ((LinearLayout) root).setDividerPadding(10);
        ((LinearLayout) root).setDividerDrawable(drawable);
    }

    mTabLayout.addTab(tabHome);
    mTabLayout.addTab(tabEmprestimos);
    mTabLayout.addTab(tabPersonal);
    mTabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
}

Solution

  • In your Drawable folder create an xml

    background.xml

    <layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    
        <item android:top="-10dp" android:right="-10dp" android:left="-10dp">
            <shape 
                android:shape="rectangle">
                <solid android:color="#1bd4f6" />
                <stroke
                    android:width="2dp"
                    android:color="#0288D1" />
            </shape>
        </item>
    
    </layer-list>
    

    Set this to your TabLayout

      <android.support.design.widget.TabLayout
            android:background="@drawable/background"
            android:id="@+id/tabs"
            android:layout_width="match_parent"
            android:layout_height="60dp"
            app:tabIndicatorColor="@color/colorAccent"
            app:tabTextColor="@color/white"/>
    

    Change values and colors as you need!

    Output:

    enter image description here