Custom font for android.support.design.widget.TabLayout

How can I use my own font for the Tablayout class belonging to the android.support.design.widget package? I use it to implement quick return functions.

+5
source share
3 answers

Try this CustomTabLayout

public class CustomTabLayout extends TabLayout { public CustomTabLayout(Context context) { super(context); } public CustomTabLayout(Context context, AttributeSet attrs) { super(context, attrs); } public CustomTabLayout(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @Override public void setTabsFromPagerAdapter(@NonNull PagerAdapter adapter) { Typeface typeface = Typeface.createFromAsset(getContext().getAssets(), "fonts/Roboto-Medium.ttf"); this.removeAllTabs(); ViewGroup slidingTabStrip = (ViewGroup) getChildAt(0); for (int i = 0, count = adapter.getCount(); i < count; i++) { Tab tab = this.newTab(); this.addTab(tab.setText(adapter.getPageTitle(i))); AppCompatTextView view = (AppCompatTextView) ((ViewGroup)slidingTabStrip.getChildAt(i)).getChildAt(1); view.setTypeface(typeface, Typeface.NORMAL); } } } 
+17
source

Starting from 23.2.0, setTabsFromPagerAdapter is deprecated, however, using a modified version of Andreyua , you can use setupWithViewPager instead.

  @Override public void setupWithViewPager(ViewPager viewPager) { super.setupWithViewPager(viewPager); if (mTypeface != null) { this.removeAllTabs(); ViewGroup slidingTabStrip = (ViewGroup) getChildAt(0); PagerAdapter adapter = viewPager.getAdapter(); for (int i = 0, count = adapter.getCount(); i < count; i++) { Tab tab = this.newTab(); this.addTab(tab.setText(adapter.getPageTitle(i))); AppCompatTextView view = (AppCompatTextView) ((ViewGroup) slidingTabStrip.getChildAt(i)).getChildAt(1); view.setTypeface(mTypeface, Typeface.NORMAL); } } } 

All credits are attributed to Andreyua for their source code fragment with minor modifications.

Unfortunately, I do not have enough reputation for comment, or I would answer directly :)

+25
source

In the Android 26.2.0 support library, you specify a font in the style

 <style name="TabLayout" parent="Widget.Design.TabLayout"> <item name="tabTextAppearance">@style/TabText</item> <item name="tabSelectedTextColor">@color/white</item> <item name="tabIndicatorColor">@color/white</item> </style> <style name="TabText" parent="TextAppearance.Design.Tab"> <item name="android:textSize">14sp</item> <item name="android:textColor">@color/lite</item> <!--Here below--> <item name="android:fontFamily">@font/gotham_medium</item> </style> 
+1
source

All Articles