繁体   English   中英

如何在自定义字体系列中获得粗体样式?

[英]How to get bold style in custom font family?

我有以下自定义字体系列代码,我想为该字体设置字体粗细

abc.xml

<?xml version="1.0" encoding="utf-8"?>
<font-family
    xmlns:android="http://schemas.android.com/apk/res/android">

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

    <font
        android:font="@font/abc_bold"
        android:fontStyle="normal"
        android:fontWeight="700" />
</font-family>

基本按钮.kt

open class BaseButton : AppCompatButton {

    @JvmOverloads
    constructor(
        context: Context,
        attrs: AttributeSet? = null,
        defStyleAttr: Int = 0)
            : super(context, attrs, defStyleAttr) {
        setFontFamily()
    }

    private fun setFontFamily() {
        val typeface = ResourcesCompat.getFont(context, R.font.abc)
        this.typeface = typeface
    }
}

screen_layout.xml

<com.aaa.bbb.ccc.BaseButton
    android:layout_width="100dp"
    android:layout_height="wrap_content"
    android:text="Test"
    android:textStyle="bold"
    android:textFontWeight="700" />

该按钮不显示粗体文本。 怎么了?

因为您是在父构造函数中设置粗体样式后设置字体的。 试试这个

    private fun setFontFamily() {
        val typeface = ResourcesCompat.getFont(context, R.font.sf_pro)
        val isBold = getTypeface().isBold

        this.setTypeface(typeface, if (isBold) Typeface.BOLD else Typeface.NORMAL)
    }

我希望这对你有用。

在布局文件中添加fontFamily属性。

<com.aaa.bbb.ccc.BaseButton
    android:layout_width="100dp"
    android:layout_height="wrap_content"
    android:text="Test"
    android:fontFamily="@font/abc_bold" />

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM