Skip to content

Instantly share code, notes, and snippets.

@ntkachov
Last active November 9, 2015 20:57
Show Gist options
  • Save ntkachov/39f208c5199d135e6ab2 to your computer and use it in GitHub Desktop.
Save ntkachov/39f208c5199d135e6ab2 to your computer and use it in GitHub Desktop.
Use this layout as a custom view inside a TabLayout.Tab to keep setText and setIcon working as usual
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- As long as BOTH these ids exist within your layout file
TabLayout will automatically pull them in.
Then you can still use setText and setIcon as usual-->
<ImageView
android:id="@android:id/icon"
android:layout_width="24dp"
android:layout_height="24dp"
android:scaleType="centerInside"/>
<com.myapplication.CustomFontTextView
android:id="@android:id/text1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
app:fontName="Gotham-Medium.ttf"/>
</LinearLayout>
public class CustomFontTabLayout extends TabLayout {
public CustomFontTabLayout(Context context) {
super(context);
}
public CustomFontTabLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CustomFontTabLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@NonNull
@Override
public Tab newTab() {
Tab tab = super.newTab();
tab.setCustomView(R.layout.custom_font_tab_layout);
if(getTabTextColors() != null){
//apply our color treatment to tabs when we create them.
setTabTextColor(tab, getTabTextColors());
}
return tab;
}
@Override
public void setTabTextColors(ColorStateList textColor) {
super.setTabTextColors(textColor);
//Custom views don't get the color treatment set it here whenever setTabTextColors gets called
for(int tabIter = 0; tabIter < this.getTabCount(); tabIter++){
setTabTextColor(getTabAt(tabIter), textColor);
}
}
private void setTabTextColor(Tab tab, ColorStateList textColor){
TextView textView = (TextView) tab.getCustomView().findViewById(android.R.id.text1);
if(textView != null){
textView.setTextColor(textColor);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment