繁体   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