如何为属于android.support.design.widget包的Tablayout类使用自定义字体?我正在使用它来实现快速返回视图功能。
答案 0 :(得分:26)
截至23.2.0,已弃用setTabsFromPagerAdapter,但使用Andreyua的修改版本的答案,您可以使用setupWithViewPager。
@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);
}
}
}
所有功劳归于Andreyua,其原始代码段稍作修改。
不幸的是,我没有足够的声誉来发表评论,或者我会直接回复:)
答案 1 :(得分:17)
试试这个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);
}
}
}
答案 2 :(得分:3)
使用android支持库26.2.0,您可以指定样式中的字体
<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>
答案 3 :(得分:0)
Kotlin Version
通过Extension Function
要将自定义字体设置为TabLayout
,请尝试在kotlin文件中添加以下代码段作为扩展功能(例如,我创建了名为Extentions.tk
的文件):
fun TabLayout.applyFont(typeface: Typeface) {
val viewGroup = getChildAt(0) as ViewGroup
val tabsCount = viewGroup.childCount
for (j in 0 until tabsCount) {
val viewGroupChildAt = viewGroup.getChildAt(j) as ViewGroup
val tabChildCount = viewGroupChildAt.childCount
for (i in 0 until tabChildCount) {
val tabViewChild = viewGroupChildAt.getChildAt(i)
if (tabViewChild is TextView) {
tabViewChild.typeface = typeface
}
}
}
}
。
Usage
现在您可以简单地按以下方式使用它:
val typeface = Typeface.createFromAsset(context.assets, "fonts/Roboto.ttf")
tabLayout.applyFont(typeface)