Gourav Khunger
Gourav Khunger

Follow

Gourav Khunger

Follow
How to change the font of text in View Pager Tabs?

How to change the font of text in View Pager Tabs?

Gourav Khunger's photo
Gourav Khunger
·Feb 8, 2021·

2 min read

Play this article

This article has been migrated from my old blog. Things may have changed since that time. If you find any wrong content in this post, please mail that to or write in the comments below. Thank you :)

Today, I am going to explain to you how can you change the text of View Pager tabs in the tabbed activity of your android app. Many times, we want to customize the minor details in our Android app, but things in Android get confusing at times. This is a very simple yet effective way. So without taking any more time, let’s dive into the codes.

First, you have to create an assets directory(please remember to keep that out of the res folder) and put your font’s .ttf file there.

Then, create a method called setCustomFont() in the tabbed activity. Code it like this:

public void setCustomFont() {

    ViewGroup vg = (ViewGroup) tabs.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(Typeface.createFromAsset(getAssets(), "font.ttf"));
            }
        }
    }
}

This code has been adapted from this answer.

Here, font.ttf is the .tff file of the font you want to use and the ViewGroup variable vg is the TabLayout in the XML with id: tabs

Change the variables to suit your needs and then call the setCustomFont() function inside the onCreate() method.

With this, you will get your desired font face of the text in the tabs. If you have any problems, understanding this, please don’t hesitate to comment!

Thumbnail art by freepik - freepik.com

Did you find this article valuable?

Support Gourav Khunger by becoming a sponsor. Any amount is appreciated!

See recent sponsors Learn more about Hashnode Sponsors
 
Share this