Dory
Dory

Reputation: 7582

Change the font of tab text in android design support TabLayout

I'm trying to work on the new TabLayout from the android design library.

I want to change tab text to custom font. And,I tried to search some styling related to TabLayout,but ended up to this.

Please guide how can I change the tab text fonts.

Upvotes: 140

Views: 116027

Answers (22)

antygravity
antygravity

Reputation: 1307

Directly changing the font of only the selected tab in a TabLayout using styles is not possible without custom code.

Here is simple Kotlin implementation with different fonts for selected and unselected tab text.

Replace Your existing <com.google.android.material.tabs.TabLayout with below implementation (<your.project.package.BoldedTabLayout).

open class BoldedTabLayout @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0) : TabLayout(context, attrs, defStyleAttr) {

private var selectedTabTypeface: Typeface? = null
private var defaultTabTypeface: Typeface? = null

init {
    selectedTabTypeface = ResourcesCompat.getFont(context, R.font.inter_bold) //Change to Your "selected" font

    defaultTabTypeface = ResourcesCompat.getFont(context, R.font.inter_semi_bold) // Change to Your "unselected" (normal) font
}

override fun addOnTabSelectedListener(listener: OnTabSelectedListener) {
    super.addOnTabSelectedListener(object : OnTabSelectedListener {
        override fun onTabSelected(tab: Tab) {
            setTabTypeface(tab, selectedTabTypeface)
            listener.onTabSelected(tab)
        }

        override fun onTabUnselected(tab: Tab) {
            setTabTypeface(tab, defaultTabTypeface)
            listener.onTabUnselected(tab)
        }

        override fun onTabReselected(tab: Tab) { //You can leave it empty but I want to ensure
            setTabTypeface(tab, selectedTabTypeface) 
            listener.onTabReselected(tab)
        }
    })
}

override fun addTab(tab: Tab, position: Int, setSelected: Boolean) {
    super.addTab(tab, position, setSelected)
    if (setSelected) {  //When creating TabLayout using addTabs( ) OnTabSelectedListener will not be called so se have to override this method to set first selected tab
        setTabTypeface(tab, selectedTabTypeface)
    }
}

fun setTabTypeface(tab: Tab, typeface: Typeface?) {
    for (i in 0 until tab.view.childCount) {
        val tabViewChild = tab.view.getChildAt(i)
        if (tabViewChild is TextView) { // We have to filter TextView (Tab text)
            tabViewChild.typeface = typeface //Here we change the font (Typeface)
        }
    }
}

}

Upvotes: 0

Suresh B B
Suresh B B

Reputation: 1420

            tabLayout = findViewById(R.id.tabLayout);
    //Update Tab layout indicator and text color
            tabLayout.setSelectedTabIndicatorColor(Color.GREY);
            tabLayout.setTabTextColors(Color.RED,Color.GREEN);
    
    //setup tablayout with view pager
            tabLayout.setupWithViewPager(viewPager);
    //after set up with view pager call update font of tablayout text
            for (int a = 0; a < tabLayout.getTabCount(); a++){
                 TabLayout.Tab selectedTab = tabLayout.getTabAt(a);
                 setTabTypeface(selectedTab, ResourcesCompat.getFont(this,R.font.dancingscript_bold));
                }

    //add this function to your class 
     private void setTabTypeface(TabLayout.Tab tab, Typeface typeface){
            for(int i=0; i<tab.view.getChildCount(); i++) {
                View tabViewChild = tab.view.getChildAt(i);
                if (tabViewChild instanceof TextView)
                    ((TextView) tabViewChild).setTypeface(typeface);
            }
        }

Upvotes: 0

Ahamadullah Saikat
Ahamadullah Saikat

Reputation: 4644

fun TabLayout.customizeTabText() {
    val viewGroup = this.getChildAt(0) as ViewGroup
    for (i: Int in 0..viewGroup.childCount) {
        val tabViewGroup = viewGroup.getChildAt(i) as ViewGroup?
        tabViewGroup?.let {
            for (j: Int in 0..tabViewGroup.childCount) {
                val tab = tabViewGroup.getChildAt(j)
                if (tab is TextView) {
                    tab.typeface = Typeface.createFromAsset(context.assets, "font.ttf")
                    tab.setTextSize(TypedValue.COMPLEX_UNIT_SP, 21f)
                }
            }
        }
    }
}

Upvotes: 0

Aminul Haque Aome
Aminul Haque Aome

Reputation: 2589

You can change Text Appearance of Tab icon by using this style written in style.xml file. here it is

<style name="TabItemTextAppearance" parent="TextAppearance.Design.Tab">
        <item name="android:textSize">13sp</item>
        <item name="fontWeight">800</item>
        <item name="fontFamily">@font/balooda2_medium</item>
</style>

and use this style in your TabLayout. Here it is

<com.google.android.material.tabs.TabLayout
                android:id="@+id/live_tab_bar"
                android:layout_width="match_parent"
                android:layout_height="@dimen/_40sdp"
                app:tabGravity="fill"
                app:tabIndicatorGravity="stretch"
                app:tabMaxWidth="0dp"
                app:tabMode="fixed"
                app:tabSelectedTextColor="@color/white"
                app:tabTextAppearance="@style/TabItemTextAppearance"
                app:tabTextColor="#354895">

                <com.google.android.material.tabs.TabItem
                    android:id="@+id/live_tab"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="লাইভ ক্লাস" />

                <com.google.android.material.tabs.TabItem
                    android:id="@+id/recorded_tab"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="রেকর্ডেড ভিডিও" />

</com.google.android.material.tabs.TabLayout>

Upvotes: 3

Nisarg
Nisarg

Reputation: 1388

If you are using

com.google.android.material:material:1.2.0 (latest version)

<style name="MyCustomTabTextAppearance" parent="TextAppearance.Design.Tab">
        <item name="fontFamily">Your Font</item>
        <item name="android:fontFamily">Your Font</item>
        <item name="textAllCaps">false</item>
    </style>

<com.google.android.material.tabs.TabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:tabBackground="@color/colorPrimary"
        app:tabGravity="fill"
        app:tabIndicatorColor="@color/white"
        app:tabMode="fixed"
        app:tabTextAppearance="@style/MyCustomTabTextAppearance"
        app:tabTextColor="@android:color/white" />

Upvotes: 23

Yvgen
Yvgen

Reputation: 2212

And here is my implementation in Kotlin that also allow change font for selected and unselected tabs.

class FontTabLayout @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    @AttrRes defStyleAttr: Int = 0
) : TabLayout(context, attrs, defStyleAttr) {

    private var textSize = 14f

    private var defaultSelectedPosition = 0

    private var selectedTypeFace: Typeface? = ResourcesCompat.getFont(context, R.font.muli_bold)
    private var normalTypeFace: Typeface? = ResourcesCompat.getFont(context, R.font.muli_regular)

    @ColorInt private var selectedColor = 0
    @ColorInt private var normalTextColor = 0

    init {
        attrs?.let { initAttrs(it) }
        addOnTabSelectedListener()
    }

    private fun initAttrs(attrs: AttributeSet) {
        val a = context.obtainStyledAttributes(attrs, R.styleable.FontTabLayout)

        textSize = a.getDimensionPixelSize(R.styleable.FontTabLayout_textSize, 14).toFloat()

        defaultSelectedPosition = a.getInteger(R.styleable.FontTabLayout_defaultSelectedPosition, 0)
        val selectedResourceId = a.getResourceId(R.styleable.FontTabLayout_selectedTypeFace, R.font.muli_bold)
        val normalResourceId = a.getResourceId(R.styleable.FontTabLayout_normalTypeFace, R.font.muli_regular)

        selectedColor = a.getColor(com.google.android.material.R.styleable.TabLayout_tabSelectedTextColor, 0)
        normalTextColor = a.getColor(R.styleable.FontTabLayout_normalTextColor, 0)

        selectedTypeFace = ResourcesCompat.getFont(context, selectedResourceId)
        normalTypeFace = ResourcesCompat.getFont(context, normalResourceId)

        a.recycle()
    }

    private fun addOnTabSelectedListener() {
        addOnTabSelectedListener(object : OnTabSelectedListenerAdapter() {

            override fun onTabUnselected(tab: Tab?) {
                getCustomViewFromTab(tab)?.apply {
                    setTextColor(normalTextColor)
                    typeface = normalTypeFace
                }
            }

            override fun onTabSelected(tab: Tab?) {

                getCustomViewFromTab(tab)?.apply {
                    setTextColor(selectedColor)
                    typeface = selectedTypeFace
                }
            }

            private fun getCustomViewFromTab(tab: Tab?) = tab?.customView as? AppCompatTextView

        })
    }

    override fun setupWithViewPager(viewPager: ViewPager?, autoRefresh: Boolean) {
        super.setupWithViewPager(viewPager, autoRefresh)
        addViews(viewPager)
    }

    private fun addViews(viewPager: ViewPager?) {
        for (i in 0 until tabCount) {
            val customTabView = getCustomTabView(i).apply {
                typeface = if (i == defaultSelectedPosition) selectedTypeFace else normalTypeFace
                val color = if (i == defaultSelectedPosition) selectedColor else normalTextColor
                setTextColor(color)
                text = viewPager?.adapter?.getPageTitle(i)
            }

            getTabAt(i)?.customView = customTabView
        }
    }

    private fun getCustomTabView(position: Int): AppCompatTextView {
        return AppCompatTextView(context).apply {
            gravity = Gravity.CENTER
            textSize = [email protected]
            text = position.toString()
        }
    }
}

in attrs.xml:

<declare-styleable name="FontTabLayout">
    <attr name="normalTextColor" format="reference|color" />
    <attr name="textSize" format="dimension" />
    <attr name="defaultSelectedPosition" format="integer" />
    <attr name="selectedTypeFace" format="reference" />
    <attr name="normalTypeFace" format="reference" />
</declare-styleable>

Upvotes: 2

Kyriakos Georgiopoulos
Kyriakos Georgiopoulos

Reputation: 567

With kotlin extension functions use this:

 fun TabLayout.setFontSizeAndColor(typeface: Typeface, @DimenRes textSize: Int, @ColorRes textColor: Int) {
val viewGroup: ViewGroup = this.getChildAt(0) as ViewGroup
val tabsCount: Int = viewGroup.childCount
for (j in 0 until tabsCount) {
    val viewGroupTab: ViewGroup = viewGroup.getChildAt(j) as ViewGroup
    val tabChildCount: Int = viewGroupTab.childCount
    for (i in 0 until tabChildCount) {
        val tabViewChild: View = viewGroupTab.getChildAt(i) as View
        if ( tabViewChild is TextView) {
            tabViewChild.typeface = typeface
            tabViewChild.gravity = Gravity.FILL
            tabViewChild.maxLines = 1
            tabViewChild.setTextSize(TypedValue.COMPLEX_UNIT_PX, this.resources.getDimension(textSize))
            tabViewChild.setTextColor(ContextCompat.getColor(this.context, textColor))
        }
    }
}

}

Upvotes: 0

Arash
Arash

Reputation: 698

As Andrei answered, you can change fontface by extending TabLayout class. And as Penzzz said, you can't do it in addTab method. Override onLayout method as bellow:

@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom){
    super.onLayout(changed, left, top, right, bottom);

    final ViewGroup tabStrip = (ViewGroup)getChildAt(0);
    final int tabCount = tabStrip.getChildCount();
    ViewGroup tabView;
    int tabChildCount;
    View tabViewChild;

    for(int i=0; i<tabCount; i++){
        tabView = (ViewGroup)tabStrip.getChildAt(i);
        tabChildCount = tabView.getChildCount();
        for(int j=0; j<tabChildCount; j++){
            tabViewChild = tabView.getChildAt(j);
            if(tabViewChild instanceof AppCompatTextView){
                if(fontFace == null){
                    fontFace = Typeface.createFromAsset(context.getAssets(), context.getString(R.string.IranSans));
                }
                ((TextView) tabViewChild).setTypeface(fontFace, Typeface.BOLD);
            }
        }
    }
}

Must Overwrite onLayout method, because, when you use setupWithViewPager method to bind the TabLayout with the ViewPager, you have to set tabs text either with setText method or in the PagerAdapter after that and when this happened, onLayout method get called on the parent ViewGroup (TabLayout) and that's the place to put setting fontface.(Changing a TextView text cause calling onLayout method of it's parent - A tabView has two children, one is ImageView another is TextView)

Another Solution:

First, these lines of code:

    if(fontFace == null){
        fontFace = Typeface.createFromAsset(context.getAssets(), context.getString(R.string.IranSans));
    }

In above solution, should be written outside of two loops.

But better solution for API >= 16 is using android:fontFamily:

Create a Android Resource Directory named font and copy your desired font to the directory.

Then use these styles:

<style name="tabLayoutTitles">
    <item name="android:textColor">@color/white</item>
    <item name="android:textSize">@dimen/appFirstFontSize</item>
    <item name="android:fontFamily">@font/vazir_bold</item>
</style>

<style name="defaultTabLayout">
    <item name="android:layout_width">match_parent</item>
    <item name="android:layout_height">@dimen/defaultTabLayoutHeight</item>
    <item name="android:gravity">right</item>
    <item name="tabTextAppearance">@style/tabLayoutTitles</item>
    <item name="tabSelectedTextColor">@color/white</item>
    <item name="tabIndicatorColor">@color/white</item>
    <item name="tabIndicatorHeight">@dimen/accomTabIndicatorHeight</item>
    <item name="tabMode">fixed</item>
    <item name="tabGravity">fill</item>
    <item name="tabBackground">@drawable/rectangle_white_ripple</item>
    <item name="android:background">@color/colorPrimary</item>
</style>

Upvotes: 11

Michał Dobi Dobrzański
Michał Dobi Dobrzański

Reputation: 2000

Kotlin extension that worked for me:

fun TabLayout.setFont(font: FontUtils.Fonts) {
    val vg = this.getChildAt(0) as ViewGroup
    for (i: Int in 0..vg.childCount) {
        val vgTab = vg.getChildAt(i) as ViewGroup?
        vgTab?.let {
            for (j: Int in 0..vgTab.childCount) {
                val tab = vgTab.getChildAt(j)
                if (tab is TextView) {
                    tab.typeface = FontUtils.getTypeFaceByFont(FontUtils.Fonts.BOLD, context)
                }
            }
        }
    }
}

Upvotes: 5

sudhakara k s
sudhakara k s

Reputation: 215

I think this is easier way.

<android.support.design.widget.TabLayout
   android:id="@+id/tabs"
   app:tabTextColor="@color/lightPrimary"
   app:tabSelectedTextColor="@color/white"
   style="@style/CustomTabLayout"
   android:layout_width="match_parent"
   android:layout_height="wrap_content"/>
<style name="CustomTabLayout" parent="Widget.Design.TabLayout">
   <item name="tabMaxWidth">20dp</item>
   <item name="tabMode">scrollable</item>
   <item name="tabIndicatorColor">?attr/colorAccent</item>
   <item name="tabIndicatorHeight">2dp</item>
   <item name="tabPaddingStart">12dp</item>
   <item name="tabPaddingEnd">12dp</item>
   <item name="tabBackground">?attr/selectableItemBackground</item>
   <item name="tabTextAppearance">@style/CustomTabTextAppearance</item>
   <item name="tabSelectedTextColor">?android:textColorPrimary</item>
</style>
<style name="CustomTabTextAppearance" parent="TextAppearance.Design.Tab">
   <item name="android:textSize">16sp</item>
   <item name="android:textStyle">bold</item>
   <item name="android:textColor">?android:textColorSecondary</item>
   <item name="textAllCaps">false</item>
</style>

Upvotes: 3

Thomas V J
Thomas V J

Reputation: 658

To use fonts support in XML feature on devices running Android 4.1 (API level 16) and higher, use the Support Library 26+.

  1. Right click res folder
  2. New -> Android resource directory-> select font -> Ok
  3. Put your myfont.ttf file in newly created font folder

On res/values/styles.xml add:

<style name="customfontstyle" parent="@android:style/TextAppearance.Small">
    <item name="android:fontFamily">@font/myfont</item>
</style>

On layout file add app:tabTextAppearance="@style/customfontstyle",

<android.support.design.widget.TabLayout
    android:id="@+id/tabs"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:tabGravity="fill"
    app:tabTextAppearance="@style/customfontstyle"
    app:tabMode="fixed" />

Please refer to [fonts in xml].(https://developer.android.com/guide/topics/ui/look-and-feel/fonts-in-xml)

Upvotes: 31

Smish jack
Smish jack

Reputation: 84

My Resolve method just like this ,change the Specified tab text ,

 ViewGroup vg = (ViewGroup) tabLayout.getChildAt(0);
 ViewGroup vgTab = (ViewGroup) vg.getChildAt(1);
 View tabViewChild = vgTab.getChildAt(1);
 if (tabViewChild instanceof TextView) {
      ((TextView) tabViewChild).setText(str);
 }

Upvotes: 3

Praveen Sharma
Praveen Sharma

Reputation: 4348

If you are using TabLayout and you want to change the font you have to add a new for loop to the previous solution like this:

private void changeTabsFont() {
    ViewGroup vg = (ViewGroup) tabLayout.getChildAt(0);
        int tabsCount = vg.getChildCount();
        for (int j = 0; j < tabsCount; j++) {
            ViewGroup vgTab = (ViewGroup) vg.getChildAt(j);
            int tabChildsCount = vgTab.getChildCount();
            for (int i = 0; i < tabChildsCount; i++) {
                View tabViewChild = vgTab.getChildAt(i);
                if (tabViewChild instanceof TextView) {
                    ((TextView) tabViewChild).setTypeface(Font.getInstance().getTypeFace(), Typeface.NORMAL);
                }
        }
    }
} 

Please refer to change font style in action bar tabs using sherlock

Upvotes: 174

Farmaan Elahi
Farmaan Elahi

Reputation: 1650

Create a TextView from Java Code or XML like this

<?xml version="1.0" encoding="utf-8"?>
<TextView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@android:id/text1"
    android:layout_width="match_parent"
    android:textSize="15sp"
    android:textColor="@color/tabs_default_color"
    android:gravity="center"
    android:layout_height="match_parent"
/>

Make sure to keep the id as it is here because the TabLayout check for this ID if you use custom textview

Then from code inflate this layout and set the custom Typeface on that textview and add this custom view to the tab

for (int i = 0; i < tabLayout.getTabCount(); i++) {
     //noinspection ConstantConditions
     TextView tv = (TextView)LayoutInflater.from(this).inflate(R.layout.custom_tab,null)
     tv.setTypeface(Typeface);       
     tabLayout.getTabAt(i).setCustomView(tv);
}

Upvotes: 41

Rafael Ruiz Mu&#241;oz
Rafael Ruiz Mu&#241;oz

Reputation: 5473

My 2p, Kotlin with reference checking, applicable everywhere as it will stop if something is wrong.

private fun setTabLayouFont(tabLayout: TabLayout) {
    val viewGroupTabLayout = tabLayout.getChildAt(0) as? ViewGroup?
    (0 until (viewGroupTabLayout?.childCount ?: return))
            .map { viewGroupTabLayout.getChildAt(it) as? ViewGroup? }
            .forEach { viewGroupTabItem ->
                (0 until (viewGroupTabItem?.childCount ?: return))
                        .mapNotNull { viewGroupTabItem.getChildAt(it) as? TextView }
                        .forEach { applyDefaultFontToTextView(it) }
            }
}

Upvotes: 1

Milind Mevada
Milind Mevada

Reputation: 3285

Create your own custom style and use parent style as parent="@android:style/TextAppearance.Widget.TabWidget"

And in your tab layout use this style as app:tabTextAppearance="@style/tab_text"

Example: Style:

<style name="tab_text" parent="@android:style/TextAppearance.Widget.TabWidget">
    <item name="android:fontFamily">@font/poppins_regular</item>
</style>

Example: Tab layout component:

<android.support.design.widget.TabLayout
        android:id="@+id/tabLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="?attr/colorPrimary"
        android:minHeight="?attr/actionBarSize"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        app:tabTextAppearance="@style/tab_text" />

Upvotes: 152

pavel
pavel

Reputation: 1671

You can use this, it works for me.

 private void changeTabsFont() {
    ViewGroup vg = (ViewGroup) tabLayout.getChildAt(0);
    int tabsCount = vg.getChildCount();
    for (int j = 0; j < tabsCount; j++) {
        ViewGroup vgTab = (ViewGroup) vg.getChildAt(j);
        int tabChildsCount = vgTab.getChildCount();
        for (int i = 0; i < tabChildsCount; i++) {
            View tabViewChild = vgTab.getChildAt(i);
            if (tabViewChild instanceof TextView) {
                AssetManager mgr = getActivity().getAssets();
                Typeface tf = Typeface.createFromAsset(mgr, "fonts/Roboto-Regular.ttf");//Font file in /assets
                ((TextView) tabViewChild).setTypeface(tf);
            }
        }
    }
}

Upvotes: 8

elsennov
elsennov

Reputation: 905

Well, i found it simple in 23.4.0 without using a loop. Just override addTab(@NonNull Tab tab, boolean setSelected) as suggested by @ejw.

@Override
public void addTab(@NonNull Tab tab, boolean setSelected) {
    CoralBoldTextView coralTabView = (CoralBoldTextView) View.inflate(getContext(), R.layout.coral_tab_layout_view, null);
    coralTabView.setText(tab.getText());
    tab.setCustomView(coralTabView);

    super.addTab(tab, setSelected);
}

And here is the XML

<?xml version="1.0" encoding="utf-8"?>
<id.co.coralshop.skyfish.ui.CoralBoldTextView
   xmlns:android="http://schemas.android.com/apk/res/android"
   android:id="@+id/custom_text"
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   android:ellipsize="end"
   android:gravity="center"
   android:singleLine="true"
   android:textColor="@color/graylove"
   android:textSize="@dimen/tab_text_size" />

Hope it could help :)

Upvotes: 7

Egis
Egis

Reputation: 5141

The following method will change font in entire ViewGroup recursively. I chose this method because you don't have to care about inner structure of TabLayout. I'm using Calligraphy library to set a font.

void changeFontInViewGroup(ViewGroup viewGroup, String fontPath) {
    for (int i = 0; i < viewGroup.getChildCount(); i++) {
        View child = viewGroup.getChildAt(i);
        if (TextView.class.isAssignableFrom(child.getClass())) {
            CalligraphyUtils.applyFontToTextView(child.getContext(), (TextView) child, fontPath);
        } else if (ViewGroup.class.isAssignableFrom(child.getClass())) {
            changeFontInViewGroup((ViewGroup) viewGroup.getChildAt(i), fontPath);
        }
    }
}

Upvotes: 16

ejw
ejw

Reputation: 151

For design support 23.2.0, using setupWithViewPager, you'll have to move the code from addTab(Tab tab) to addTab(Tab tab, boolean setSelected).

Upvotes: 10

Penzzz
Penzzz

Reputation: 2973

Change

if (tabViewChild instanceof TextView) {

for

if (tabViewChild instanceof AppCompatTextView) { 

to make it work with android.support.design.widget.TabLayout (at least from com.android.support:design:23.2.0)

Upvotes: -2

Andrei Aulaska
Andrei Aulaska

Reputation: 1118

Great answer from praveen Sharma. Just a small addition: Instead of using changeTabsFont() everywhere you need TabLayout, you can simply use your own CustomTabLayout.

import android.content.Context;
import android.graphics.Typeface;
import android.support.design.widget.TabLayout;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class CustomTabLayout extends TabLayout {
    private Typeface mTypeface;

    public CustomTabLayout(Context context) {
        super(context);
        init();
    }

    public CustomTabLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public CustomTabLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        mTypeface = Typeface.createFromAsset(getContext().getAssets(), "fonts/Roboto-Regular.ttf");
    }

    @Override
    public void addTab(Tab tab) {
        super.addTab(tab);

        ViewGroup mainView = (ViewGroup) getChildAt(0);
        ViewGroup tabView = (ViewGroup) mainView.getChildAt(tab.getPosition());

        int tabChildCount = tabView.getChildCount();
        for (int i = 0; i < tabChildCount; i++) {
            View tabViewChild = tabView.getChildAt(i);
            if (tabViewChild instanceof TextView) {
                ((TextView) tabViewChild).setTypeface(mTypeface, Typeface.NORMAL);
            }
        }
    }

}

And one more thing. TabView is a LinearLayout with TextView inside (it can also optionally contain ImageView). So you can make the code even simpler:

@Override
public void addTab(Tab tab) {
    super.addTab(tab);

    ViewGroup mainView = (ViewGroup) getChildAt(0);
    ViewGroup tabView = (ViewGroup) mainView.getChildAt(tab.getPosition());
    View tabViewChild = tabView.getChildAt(1);
    ((TextView) tabViewChild).setTypeface(mTypeface, Typeface.NORMAL);
}

But I wouldn't recommend this way. If TabLayout implementation will change, this code can work improperly or even crash.

Another way to customise TabLayout is adding custom view to it. Here is the great example.

Upvotes: 50

Related Questions