A brief introduction to the separator of custom TabLayout

You must be familiar with using custom TabLayout as the indicator of ViewPager. If you don't know about custom TabLayout, you can have a look at it Showdy Written Custom style of TabLayout .

In this article, I will not repeat too much about how to customize the style of TabLayout, but simply talk about how to customize the separator Divider of TabLayout.

As shown in the figure below, it is the page effect to be realized:

It can be seen that unlike the General Tab indicator of ViewPager, there is no indicator bar below the text, instead, there is a separator between tabs, and this separator has the requirement of upper and lower spacing.

Nonsense, show me the fxcking code directly!!!

tab in activity:

        android:background="#ffffff"   //Set background color
        app:tabIndicatorHeight="0dp"   //Horizontal bar height set to0dp
        app:tabSelectedTextColor="#FEDA44" //tab selected color
        app:tabTextColor="#000000">   //Unselected text color

The custom style file Divider vertical.xml for the separator dividerunder the drawable folder:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="#EDECEB"/>
    <size android:width="1dp"/>
    <padding android:bottom="9dp"/>
    <padding android:top="9dp"/>

Set in Java file:

mTabs.setTabMode(TabLayout.MODE_FIXED); //This mode can be used when there are fewer tabs and the screen is full;
mTabs.setTabGravity(TabLayout.GRAVITY_FILL); //Used with TabMode to divide the full width of TabLayout equally for each label
LinearLayout linearLayout = (LinearLayout) mTabs.getChildAt(0);
linearLayout.setDividerDrawable(ContextCompat.getDrawable(this, R.drawable.divider_vertical)); //Set the drawable of the divider
linearLayout.setDividerPadding(SizeUtils.dip2px(this, 9));   //The parameter passed in by this method is the size of pixel, so the method of dp to px is needed

So far, we have implemented the method of customizing the separation line of TabLayout. Have you also found the power of TabLayout? This article is very short, which is still very useful. If any little partner encounters such a problem, this article helps you solve the doubt. Please like it

Tags: Android xml encoding Java

Posted on Fri, 20 Mar 2020 13:13:28 -0700 by Moocat