Skip to content

Instantly share code, notes, and snippets.

@luongvo
Forked from LuigiPapino/FontAwareTabLayout.java
Created June 12, 2017 21:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save luongvo/17f84a57a12af15c5a24b1435fc056be to your computer and use it in GitHub Desktop.
Save luongvo/17f84a57a12af15c5a24b1435fc056be to your computer and use it in GitHub Desktop.
Android - Calligraphy and TabLayout
/**
* Simple helper class which extends a TabLayout to allow us to customize the font of the tab.
* https://gist.github.com/tmtrademarked/09926077a406959be15fc8a824a52751
* https://github.com/chrisjenx/Calligraphy/issues/180
*/
public final class FontAwareTabLayout extends TabLayout {
private String fontPath;
public FontAwareTabLayout(Context context, AttributeSet attrs) {
super(context, attrs);
fontPath = pullFontPathFromView(context, attrs, new int[] { R.attr.fontPath });
}
/**
* Tries to pull the Custom Attribute directly from the TextView.
*
* @param context Activity Context
* @param attrs View Attributes
* @param attributeId if -1 returns null.
* @return null if attribute is not defined or added to View
*/
static String pullFontPathFromView(Context context, AttributeSet attrs, int[] attributeId) {
if (attributeId == null || attrs == null) return null;
final String attributeName;
try {
attributeName = context.getResources().getResourceEntryName(attributeId[0]);
} catch (Resources.NotFoundException e) {
// invalid attribute ID
return null;
}
final int stringResourceId = attrs.getAttributeResourceValue(null, attributeName, -1);
return stringResourceId > 0 ? context.getString(stringResourceId)
: attrs.getAttributeValue(null, attributeName);
}
@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) {
CalligraphyUtils.applyFontToTextView(getContext(), (TextView) tabViewChild, fontPath);
}
}
}
}
<com.adaptics.dropkitchen.ui.base.widget.FontAwareTabLayout
android:id="@+id/browser_tab"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:animateLayoutChanges="true"
android:background="?attr/colorPrimary"
android:theme="@style/AppTheme.AppBarOverlay"
app:layout_scrollFlags="scroll|enterAlways"
app:tabBackground="@color/white"
app:tabGravity="center"
app:tabMode="scrollable"
app:tabSelectedTextColor="@color/colorPrimary"
app:tabTextAppearance="@style/RecipesBrowserTabTextStyle"
fontPath="@string/common_fonts_sans_condensed_bold"
/>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment