如何在font_family.xml中设置自定义字体,其属性为android:fontStyle =“bold”

时间:2018-04-27 06:09:01

标签: android android-xml font-family android-fonts

我想在font_family.xml中添加自定义粗体字体。我在font family developer doc中找不到粗体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. 如何在字体系列中添加自定义粗体字体并在android:fontStyle="bold"中设置font_family.xml,这样我就不必创建不同的样式,我只需设置textStyle="bold"
  3. 那么什么是我可以设置我的3种字体的解决方案 - normal, bold, italic到font_family.xml,并在TextView上设置android:fontFamily="@font/font_family"然后我可以使用android:textStyle="bold"或斜体,或者正常?

3 个答案:

答案 0 :(得分:3)

关于您的第二个问题

通过使用 font-family 定义字体,您可以在fontWeight="700"中添加自定义粗体字体:

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

如果TextViewfont-family一起使用此fontStyle="bold",它将显示在 montserrat_semi_bold

答案 1 :(得分:0)

以这种方式以编程方式设置字体粗体

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

或者

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

或您可以使用绘画对象并将其设置为文本

答案 2 :(得分:-1)

您可以通过在layout.xml中应用名为 android:textStyle 的属性来实现此目的 你可以这样做:

<TextView 
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textStyle="bold" />
相关问题