styles.xml中的Android Studio 3.0自定义字体

时间:2017-10-24 08:09:55

标签: android fonts android-support-library android-studio-3.0

我无法在样式文件中设置自定义字体。

<resources>
    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        ...
        <item name="android:textViewStyle">@style/fontTextView</item>
        ...
    </style>

    <style name="fontTextView" parent="@android:style/Widget.TextView">
        <item name="android:fontFamily">@font/example</item>
    </style>
</resources>

我仍在我的应用中看到默认字体。但是,当我将fontFamily更改为其中一个默认值时,它会更改

    <style name="fontTextView" parent="@android:style/Widget.TextView">
        <item name="android:fontFamily">monospace</item>
    </style>

如果我以编程方式设置自定义字体,它也有效。

setTypeface(ResourcesCompat.getFont(context, R.font.example));

如何使其适用于styles.xml中的自定义字体?

我将compiltSdkVersion设为26,将buildToolsVersion设为26.0.2。我也在使用支持库:

  def supportVersion = '26.1.0'
  implementation "com.android.support:appcompat-v7:$supportVersion"

我的字体系列:

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

    app:fontStyle="normal"
    app:fontWeight="300"
    app:font="@font/example_regular"/>

<font
    android:fontStyle="normal"
    android:fontWeight="400"
    android:font="@font/example_regular"

    app:fontStyle="normal"
    app:fontWeight="400"
    app:font="@font/example_regular"/>

<font
    android:fontStyle="normal"
    android:fontWeight="400"
    android:font="@font/example_regular"

    app:fontStyle="normal"
    app:fontWeight="700"
    app:font="@font/example_regular"/>

<font
    android:fontStyle="italic"
    android:fontWeight="400"
    android:font="@font/example_regular"

    app:fontStyle="italic"
    app:fontWeight="300"
    app:font="@font/example_regular" />

<font
    android:fontStyle="italic"
    android:fontWeight="400"
    android:font="@font/example_regular"

    app:fontStyle="italic"
    app:fontWeight="400"
    app:font="@font/example_regular" />

<font
    android:fontStyle="italic"
    android:fontWeight="400"
    android:font="@font/example_regular"

    app:fontStyle="italic"
    app:fontWeight="700"
    app:font="@font/example_regular" />

</font-family>

我使用相同的*ttf文件进行测试。

2 个答案:

答案 0 :(得分:2)

确定。我解决了这个问题 - 这种行为的原因非常简单......我正在扩展Activity而不是AppCompatActivity

答案 1 :(得分:1)

使用自定义字体进行xml设计: 首先,您需要在资源目录中创建字体文件夹  将所有自定义字体(.ttf文件)文件放入字体文件夹中。 然后在xml设计中添加属性fontFamily。 喜欢  

    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hello World!"
    android:textSize="40dp"
    android:fontFamily="@font/semibold"/>

使用该链接https://developer.android.com/guide/topics/ui/look-and-feel/fonts-in-xml.html