Search code examples
javaandroidtabsandroid-tablayout

TabLayout set text size of TabLayout.Tab from code (programmatically)


I'm trying to set up a text size from code, since this option does not exist does anyone have an idea how to achieve this?

I know it's possible through style, but I can't use style.

Also I tried this example, but it doesn't work.

I have partially (some Tabs get new text size) succes with this:

try {
        Field tabTextSize = TabLayout.class.getDeclaredField("mTabTextSize");
        tabTextSize.setAccessible(true);
        tabTextSize.setFloat(mTabLayout, 64f);
    } catch (Exception e) {
        e.printStackTrace();
    }

Solution

  • try this

    Create an xml layout named custom_tab.xml

    <?xml version="1.0" encoding="utf-8"?>
    <TextView xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/tab"
        android:textColor="@color/colorAccent"/>
    

    than in your activity set text size programaticlly like below code

    TextView tabOne = (TextView) LayoutInflater.from(this).inflate(R.layout.custom_tab, null);
    tabOne.setText("ONE");
    tabOne.setTextSize(14); // set font size as per your requirement 
    tabLayout.getTabAt(0).setCustomView(tabOne);