[英]How to change the font of tabLayout with a custom font / calligraphy
我正在寻找有关如何将TabLayout中这些选项卡的字体更改为自定义字体的答案。
我试过这个,但它没有用
Typeface hero = Typeface.createFromAsset(getContext().getAssets(),"fonts/Hero Light.otf");
textViewToConvert.setTypeface(hero);
}
}
在你的布局中
<android.support.design.widget.TabLayout
android:id="@+id/sliding_tabs"
style="@style/Tab"
android:layout_width="match_parent"
android:layout_height="54dp"
app:tabTextAppearance="@style/MineCustomTabText"/>
并在您的样式文件夹中
<style name="MineCustomTabText" parent="TextAppearance.Design.Tab">
<item name="android:textSize">12sp</item>
<item name="android:textAllCaps">true</item>
<item name="android:fontFamily">@font/two_light_1</item>
</style>
我们通过造型来做到这一点。 首先定义选项卡中的文本具有特殊样式:
<android.support.design.widget.TabLayout
app:tabTextAppearance="@style/transactions__month_tabs_text_appearance">
然后在样式中定义您要使用自定义字体:
<style name="transactions__month_tabs_text_appearance" parent="TextAppearance.Design.Tab">
<item name="fontPath">fonts/your-font-name.ttf</item>
</style>
顺便说一句,我们将所有字体名称都放在字符串资源上
像这样从Java代码或XML创建TextView(确保保留该id)
<?xml version="1.0" encoding="utf-8"?>
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@android:id/text1"
android:layout_width="match_parent"
android:textSize="15sp"
android:textColor="@color/tabs_default_color"
android:gravity="center"
android:layout_height="match_parent"
/>
然后从代码
for (int i = 0; i < tabLayout.getTabCount(); i++) {
//R.layout is the previous defined xml
TextView tv=(TextView)LayoutInflater.from(this).inflate(R.layout.custom_tab,null)
tv.setTypeface(Typeface);
tabLayout.getTabAt(i).setCustomView(tv);
}
我在我的项目中使用这种方法并且工作得非常好,如果我愿意的话,我可以在将来在应用程序的不同位置自定义选项卡字体和bg颜色。
public static void changeTabsFont(Context context, TabLayout tabLayout, int color) {
ViewGroup vg = (ViewGroup) tabLayout.getChildAt(0);
tabLayout.setBackgroundColor(color);
int tabsCount = vg.getChildCount();
for (int j = 0; j < tabsCount; j++) {
ViewGroup vgTab = (ViewGroup) vg.getChildAt(j);
int tabChildsCount = vgTab.getChildCount();
for (int i = 0; i < tabChildsCount; i++) {
View tabViewChild = vgTab.getChildAt(i);
if (tabViewChild instanceof TextView) {
((TextView) tabViewChild).setTypeface(Typeface.createFromAsset(context.getAssets(), "Lato-Regular.ttf"));
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.