可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I was looking for answers about how I can change the fonts of those tabs in that TabLayout to a custom font.
I tried this but it didnt work
Typeface hero = Typeface.createFromAsset(getContext().getAssets(),"fonts/Hero Light.otf"); textViewToConvert.setTypeface(hero); } }
回答1:
In your layout
<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"/>
and in your style folder
<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>
回答2:
We do it through styling. First define that text in tab has special style:
<android.support.design.widget.TabLayout app:tabTextAppearance="@style/transactions__month_tabs_text_appearance">
And then in style define that you want to use custom font:
<style name="transactions__month_tabs_text_appearance" parent="TextAppearance.Design.Tab"> <item name="fontPath">fonts/your-font-name.ttf</item> </style>
BTW, we put all font names to string resources.
回答3:
Create a TextView from Java Code or XML like this (Make sure to keep that 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" />
Then from code
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); }
回答4:
I am using this method in my project and works very well, its efficient in a way where I can customize tab fonts and bg color in future at different places in the app if I want.
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")); } } } }