Search code examples
androidandroid-viewpagerandroid-tabstrip

How to change the font of PagerTabStrip


I'm using a ViewPager with a PagerTabStrip and I need to set custom fonts (typeface) , but there is no .setTypeFace function for PagerTabStrip!

Here is my XML code:

 <android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/viewPager"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <android.support.v4.view.PagerTabStrip
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/pagerTabStrip"
        android:layout_gravity="top"
        android:background="#FF0000"
        android:textColor="#FFFFFF" />

</android.support.v4.view.ViewPager>

According to this link, I found a solution that may solve my problem.

Get the child views of the PagerTabStrip and check if it is an instance of a TextView. If it is, set the typeface:

for (int i = 0; i < pagerTabStrip.getChildCount(); ++i) {
View nextChild = pagerTabStrip.getChildAt(i);
if (nextChild instanceof TextView) {
   TextView textViewToConvert = (TextView) nextChild;
   textViewToConvert.setTypeface(PUT_TYPEFACE_HERE)
}
}

But I don't understand what it means.

My layout is:

Image

I want to change the title tab to another font style,.like below:

Image


Solution

  • You need to do is create a style for the text, and then use the android:textAppearance attribute...

    Something like this:

     <style name="PagerTabStripText">
         <item name="android:textStyle">italic</item>
     </style>
    

    Your PagerTabStrip XML will be like this:

    <android.support.v4.view.PagerTabStrip
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/pagerTabStrip"
        android:layout_gravity="top"
        android:background="#FF0000"
        android:textColor="#FFFFFF"
        android:textAppearance="@style/PagerTabStripText" />