Search code examples
androidandroid-viewpagertext-size

How to change Android ViewPager page title text size depending on the screen size


Having 3 pages in the ViewPager and running on a tablet vs running on a smartphone the text size for the page title must change.

any ide?

I try to set PagerTabStrip text size in the xml but that was not possible

<android.support.v4.view.ViewPager
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/pager"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="?android:attr/windowBackground">

    <android.support.v4.view.PagerTabStrip
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

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

Solution

  • I try to set PagerTabStrip text size in the xml but that was not possible

    Did you? Because you can definitely do that. If you take a look at the PagerTitleStrip source you'll see it uses the following attributes to style the title text.

    private static final int[] ATTRS = new int[] {
        android.R.attr.textAppearance,
        android.R.attr.textSize,
        android.R.attr.textColor,
        android.R.attr.gravity
    };
    

    And you can set any one of those in your XML, so in your case something like:

        <android.support.v4.view.PagerTabStrip
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textSize="@dimen/pagerTitleTextSize" />
    

    Where pagerTitleTextSize is just a text size in whatever values folder you need. For instance:

    values

    <resources>
    
        <dimen name="pagerTitleTextSize">22sp</dimen>
    
    </resources>
    

    phone

    values-sw600dp

    <resources>
    
        <dimen name="pagerTitleTextSize">64sp</dimen>
    
    </resources>
    

    tablet

    There's also PagerTitleStrip.setTextSize if you wanted to handle it programmatically.