Change the font of tab text in android TabLayout programetically



 res/layout/activity_main.xml
<? xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >

    <android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        android:background="@color/colorPrimary"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        android:layout_gravity="bottom"   >
    </android.support.design.widget.TabLayout>
   </android.support.v4.view.ViewPager>
</ android.support.constraint.ConstraintLayout>


MainActivity.java
package com.example.geekscompete.tablayouttextfontdemo;

import android.graphics.Color;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    TabLayout tabs;
    ViewPager viewPager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        viewPager=findViewById(R.id.viewpager);
        tabs=findViewById(R.id.tabs);

        tabs.addTab(tabs.newTab().setText("Tab 1"));
        tabs.addTab(tabs.newTab().setText("Tab 2"));
        tabs.addTab(tabs.newTab().setText("Tab 3"));
        tabs.setTabTextColors(getResources().getColor(R.color.lime),getResources().getColor(R.color.colorAccent));
        changeTabsFont();
}
    private void changeTabsFont() {
      ViewGroup childTabLayout = (ViewGroup) tabs.getChildAt(0);
      for (int i = 0; i < childTabLayout.getChildCount(); i++) {
        ViewGroup viewTab = (ViewGroup) childTabLayout.getChildAt(i);
        for (int j = 0; j < viewTab.getChildCount(); j++) {
          View tabTextView = viewTab.getChildAt(j);
          if (tabTextView instanceof TextView) {
            Typeface typeface = Typeface.createFromAsset(getAssets(), "fonts/OpenSans-Regular.ttf");
            ((TextView) tabTextView).setAllCaps(false);
            ((TextView) tabTextView).setTypeface(typeface);
         }
        }
      }
    }
}

No comments:

Post a Comment

Popular Posts