138

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.

Mario Velasco
  • 3,336
  • 3
  • 33
  • 50
Dory
  • 7,462
  • 7
  • 33
  • 55

21 Answers21

174

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

Barry
  • 3,303
  • 7
  • 23
  • 42
Praveen Sharma
  • 4,326
  • 5
  • 25
  • 45
  • I am not using M preview. Is there any other way to do it. – Dory Jun 26 '15 at 08:38
  • 1
    You don't need M preview, it is valid for everyone using `TabLayout` – Mario Velasco Oct 06 '15 at 16:26
  • However, I'm encountering a NullPointerException on android.view.View android.support.design.widget.TabLayout.getChildAt(int), can you help me how to fix it? Can't find what am I missing on my code. – brettbrdls Apr 13 '16 at 04:05
  • 1
    The first parameter of `setTypeFace` is a `TypeFace`, in case if you can't find the `Font` class (which doesn't appear to exist for me) – Vahid Amiri Nov 19 '16 at 23:38
149

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" />
Milind Mevada
  • 3,145
  • 1
  • 14
  • 22
  • 14
    This is correct, I'm using `parent="TextAppearance.Design.Tab"` in my case. – Javatar Oct 18 '17 at 13:32
  • 2
    This works much better than first answers, and without black magic (hidden api), which could break something in the future – Sulfkain Apr 20 '18 at 09:08
  • 2
    just work when use fontFamily, not work when use fontPath – Tram Nguyen May 17 '18 at 17:21
  • 2
    I was getting weird exceptions erratically when using `TextAppearance.Widget.TabWidget`. @Javatar 's answer fixed it for me. – funct7 Sep 16 '19 at 13:29
  • 2
    I'm using `com.google.android.material.tabs.TabLayout` so my style's parent is `Widget.MaterialComponents.TabLayout`, other than that same solution, works great, thanks. – ProjectDelta Jul 20 '21 at 09:29
49

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.

Andrei Aulaska
  • 1,098
  • 14
  • 22
  • addTab wiil not invoke in case you set tabs like this: mViewPager.setAdapter(new YourPagerAdapter(getChildFragmentManager())); mTabLayout.setupWithViewPager(mViewPager); – Penzzz Mar 04 '16 at 09:53
  • 2
    @Penzzz you are absolutely right. In this case you should move the code from addTab method to another. For example onMeasure. – Andrei Aulaska Mar 04 '16 at 12:19
  • @AndreiAulaska thnx You save my day . Your last Link save me. – Amol Dale Mar 16 '16 at 12:17
  • this does not work anymore i think in latest version. @ejw's answer is now working. need to add it in addTab(Tab tab, boolean setSelected) – Sayem Sep 23 '16 at 11:25
  • 3
    This works well. NOTE: as of support library 25.x, you need to override `addTab(Tab tab, int position, boolean setSelected)` instead of `addTab(Tab tab)`. – Vicky Chijwani Jun 17 '17 at 23:18
41

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);
}
Barry
  • 3,303
  • 7
  • 23
  • 42
Farmaan Elahi
  • 1,620
  • 16
  • 18
31

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)

Barry
  • 3,303
  • 7
  • 23
  • 42
Thomas V J
  • 658
  • 8
  • 7
20

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" />
Nisarg
  • 1,358
  • 14
  • 30
16

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);
        }
    }
}
Egis
  • 5,081
  • 5
  • 39
  • 61
  • 1
    problem with this is, if you attach the layout to a Viewpager, you will lose the customized fonts. – rupps Oct 10 '17 at 19:57
11

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>
Arash
  • 696
  • 8
  • 24
  • This is a bad performance fix, `onLayout()` got called with every layout change like tab switching or even list scrolling below the tabs, with nested `for`s in a many tabs `TabLayout` app will be lagy. – Amr Barakat Nov 09 '17 at 06:04
  • 2
    @Amr Barakat. According to this link: https://developer.android.com/reference/android/view/View.html#onLayout(boolean, int, int, int, int), this is not true. I tested it too. I put a break point in **onLayout** method and it's get called when the tabs are being created not on tab switching or list scrolling. – Arash Nov 09 '17 at 10:30
  • 1
    For me `onLayout()` does get called multiple times when tab switching (not sure why exactly), but to account for this I only set the fonts when the `boolean changed` is true. Doing that prevents setting the fonts multiple times. – Robert Nov 12 '18 at 21:00
  • great solution, no code required, only xml attributes – careful7j Sep 13 '19 at 17:52
10

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).

ejw
  • 151
  • 1
  • 5
8

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);
            }
        }
    }
}
pavel
  • 1,603
  • 22
  • 19
7

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 :)

elsennov
  • 875
  • 9
  • 14
4

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)
                }
            }
        }
    }
}
Michał Dobi Dobrzański
  • 1,449
  • 1
  • 20
  • 19
3

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);
 }
Barry
  • 3,303
  • 7
  • 23
  • 42
Smish jack
  • 84
  • 11
3
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>
sudhakara k s
  • 217
  • 3
  • 8
2

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 = this@FontTabLayout.textSize
            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>
Yvgen
  • 2,036
  • 2
  • 23
  • 27
1

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) }
            }
}
Rafael Ruiz Muñoz
  • 5,333
  • 6
  • 46
  • 92
1

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>
Aminul Haque Aome
  • 2,261
  • 21
  • 34
0

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))
        }
    }
}

}

0
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)
                }
            }
        }
    }
}
Ahamadullah Saikat
  • 4,437
  • 42
  • 39
0
            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);
            }
        }
Suresh B B
  • 1,387
  • 11
  • 13
-2

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)

Penzzz
  • 2,814
  • 17
  • 23