簡體   English   中英

如何在 font_family.xml 中使用屬性 android:fontStyle="bold" 設置自定義字體

[英]How to set custom font in font_family.xml with attribute android:fontStyle=“bold”

我想在我的font_family.xml添加自定義粗體字體。 我在字體系列開發人員文檔中沒有找到粗體fontStyle="bold" 它只有normalitalic屬性。 這是font_family.xml

<?xml version="1.0" encoding="utf-8"?>
<font-family xmlns:android="http://schemas.android.com/apk/res/android">
    <font
        android:fontStyle="normal"
        android:fontWeight="400"
        android:font="@font/lobster_regular" />
    <font
        android:fontStyle="italic"
        android:fontWeight="400"
        android:font="@font/lobster_italic" />
</font-family>

所以我必須使用像

<style name="fontBoldStyle" parent="@android:style/TextAppearance.Small">
    <item name="android:fontFamily">@font/montserrat_semi_bold</item>
</style>

或者像這樣

<TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:fontFamily="@font/montserrat_semi_bold"/>

我的問題

  1. fontStyle屬性有什么作用? 即使我沒有為font_family.xml提供斜體字體,並設置textStyle="italic"然后我的字體是斜體。
  2. 如何在字體系列中添加自定義粗體並在font_family.xml設置android:fontStyle="bold"所以我不必創建不同的樣式,我只需要設置textStyle="bold"

那么什么是我可以設置 3 種字體的解決方案 - normal, bold, italic到 font_family.xml,並在 TextView 上設置android:fontFamily="@font/font_family"然后我可以使用android:textStyle="bold"或斜體,或正常?

對於您的第二個問題

您可以通過使用fontWeight="700"定義字體,在font-family添加自定義粗體字體:

<font-family xmlns:android="http://schemas.android.com/apk/res/android">
    <font
        android:fontStyle="normal"
        android:fontWeight="400"
        android:font="@font/lobster_regular" />
    <font
        android:fontStyle="italic"
        android:fontWeight="400"
        android:font="@font/lobster_italic" />
    <font
        android:fontStyle="normal"
        android:fontWeight="700"
        android:font="@font/montserrat_semi_bold" />
</font-family>

如果TextView使用帶有textStyle="bold" font-family ,它將顯示在montserrat_semi_bold

有一種方法可以通過在android:textStyle中應用名為android:textStyle屬性來執行此操作,您可以執行以下操作:

<TextView 
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textStyle="bold" />

以這種方式以編程方式設置字體粗體

mTextView.setTypeface(Typeface.ttf, Typeface.BOLD);

或者

mTextView.setTypeface(mTextView.getTypeface(), Typeface.BOLD);

或者您可以使用繪畫對象並將其設置為文本

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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