【问题标题】:Android: Custom font works for TextView, not for ButtonAndroid:自定义字体适用于 TextView,不适用于 Button
【发布时间】:2018-06-06 16:50:14
【问题描述】:

我无法获得按钮来使用我的自定义字体。 它适用于 TextView,而不是 Button(它是 TextView 的子类)。

我正在使用带有 minSdkVersion 26 和 Kotlin 的 Android Studio 3.1.2。

res/font/font.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/my-custom-font" />
</font-family>

res/layout/fragment.xml

...
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/myButton"
    android:maxWidth="30dp"
    android:minWidth="30dp"
    android:maxHeight="40dp"
    android:minHeight="40dp"
    android:fontFamily="@font/my-custom-font"
    android:textSize="20dp"
    android:text="a" />
...

以上工作。将 TextView 替换为 Button 并停止工作。

编辑:我想使用自定义字体来保存按钮的图标,而不是使用图像和 ImageButtons。我们发现自定义字体比图像更易于管理。

【问题讨论】:

  • 按钮不是默认粗体吗?您的字体没有提供粗体样式
  • @SamuelEminet 根据Fonts documentation 我只能将fontStyle 设置为normalitalic
  • 要添加粗体样式,请添加粗细约为 700 的字体android:fontWeight="700"
  • 感谢@SamuelEminet,但我不想让它变粗,只是为了使用我的自定义字体。如果我为 Button 使用标准字体,它会以正常重量显示。

标签: android button kotlin textview custom-font


【解决方案1】:

为您的按钮添加样式:

styles.xml下新建样式:

<style name="main_button">
    <item name="android:fontFamily">@font/my-custom-font</item>
    <item name="android:background">@drawable/btn_blue</item>
    <item name="android:textColor">#FFFF</item>
    <item name="android:textAllCaps">false</item>
    <item name="android:foreground">?attr/selectableItemBackground</item>
</style>

输入您想要的任何值。确保包含fontFamily:

然后在你的按钮上,添加样式:

<Button
    android:id="@+id/id"
    style="@style/main_button" />

【讨论】:

  • 另外,您的回复给了我一个提示:如果我只是将android:textAllCaps="false" 添加到我的按钮,它确实有效。我猜按钮默认使用全部大写,到目前为止我只映射了小写字符。总而言之:虽然使用样式可以为许多按钮指定一次属性并且可能很有用,但自定义字体确实适用于按钮。
  • @FabioKatz 完美!我喜欢使用样式,因为重复使用相同样式时复制和粘贴的次数更少!很高兴它对你有所帮助
【解决方案2】:

在你的风格中使用app:fontFamily="@font/my-custom-font",而不是android:fontFamily="@font/my-custom-font"

【讨论】:

    猜你喜欢
    • 2012-10-28
    • 1970-01-01
    • 1970-01-01
    • 2015-07-28
    • 1970-01-01
    • 1970-01-01
    • 2023-03-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多