Skip to content

Instantly share code, notes, and snippets.

@tmtrademarked
Created January 5, 2017 00:10
Show Gist options
  • Save tmtrademarked/09926077a406959be15fc8a824a52751 to your computer and use it in GitHub Desktop.
Save tmtrademarked/09926077a406959be15fc8a824a52751 to your computer and use it in GitHub Desktop.
SImple wrapper class to support fonts in TabLayout
/**
* Simple helper class which extends a TabLayout to allow us to customize the font of the tab.
*/
public final class FontTabLayout extends TabLayout {
// TODO - support customizing via XML rather than hardcoding.
private static final String FONT_PATH = "fonts/Roboto.ttf";
private Typeface mTypeface;
public FontTabLayout(Context context) {
super(context);
init();
}
public FontTabLayout(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public FontTabLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
mTypeface = Typeface.createFromAsset(getContext().getAssets(), FONT_PATH);
}
@Override
public void addTab(@NonNull Tab tab, int position, boolean setSelected) {
super.addTab(tab, position, setSelected);
ViewGroup mainView = (ViewGroup) getChildAt(0);
ViewGroup tabView = (ViewGroup) mainView.getChildAt(tab.getPosition());
int tabChildCount = tabView.getChildCount();
for (int i = 0; i < tabChildCount; i++) {
View tabViewChild = tabView.getChildAt(i);
if (tabViewChild instanceof TextView) {
((TextView) tabViewChild).setTypeface(mTypeface, Typeface.NORMAL);
}
}
}
}
@icarovirtual
Copy link

Nice one! Works like a charm!

@gordinmitya
Copy link

gordinmitya commented May 24, 2017

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment