android - 如何在自定义字体系列中获得粗体样式?
问题描述
我有以下自定义字体系列代码,我想为该字体设置字体粗细
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)
}
推荐阅读
- multithreading - OWLAPI API 是线程安全的吗?
- php - 如何从单个模型中打印出两个急切加载的关系
- asp.net - 为什么远程调试器无法运行?
- python - 真正进口的是什么?
- c++ - 如何用 atomic 保证数据依赖?
- css - 有没有办法增加 JavaFX ProgressIndicator 组件的厚度?
- r - 如何在highcharter悬停时获得系列亮点?
- sql - 我需要算术 SQL 查询
- java - 如何在 java 中解析 BluetoothGattCharacteristic 值
- intellij-idea - 在 Intelij IDEA 中使用自定义脚本运行 sbt shell