Search code examples
androidfontsandroid-design-libraryandroid-fontsandroid-tablayout

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.


Solution

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