簡體   English   中英

如何使用自定義字體/書法更改tabLayout的字體

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM