继承AppCompatTextView引入字体包,后续直接使用MyFontTextView 即可
open class MyFontTextView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : AppCompatTextView(context, attrs, defStyleAttr) {
private var currentWeight = 400
private var isItalic = false
init {
applyCustomFont(context, attrs)
}
private fun applyCustomFont(context: Context, attrs: AttributeSet?) {
if (attrs != null) {
for (i in 0 until attrs.attributeCount) {
when (attrs.getAttributeNameResource(i)) {
android.R.attr.textFontWeight -> {
currentWeight = attrs.getAttributeIntValue(i, 400)
}
android.R.attr.textStyle -> {
val style = attrs.getAttributeIntValue(i, Typeface.NORMAL)
isItalic = (style == Typeface.ITALIC || style == Typeface.BOLD_ITALIC)
}
}
}
}
typeface = FontCache.getInterTypeface(context, currentWeight, isItalic)
}
fun setFontWeight(weight: Int) {
if (currentWeight != weight) {
currentWeight = weight
updateCustomTypeface()
}
}
private fun updateCustomTypeface() {
val newTypeface = FontCache.getInterTypeface(context, currentWeight, isItalic)
if (typeface != newTypeface) {
typeface = newTypeface
}
}
}
字体包缓存类
import android.content.Context
import android.graphics.Typeface
import androidx.core.content.res.ResourcesCompat
object FontCache {
private val cache = mutableMapOf<String, Typeface?>()
private val weights = listOf(400, 500, 600, 700, 800, 900)
private val italics = listOf(false, true)
fun init(context: Context) {
for (weight in weights) {
for (italic in italics) {
getInterTypeface(context, weight, italic)
}
}
}
/**
* 获取 Inter 字体,根据权重 & italic 自动选择
*/
fun getInterTypeface(context: Context, weight: Int, italic: Boolean): Typeface? {
val key = "$weight-$italic"
cache[key]?.let { return it }
val resId = when (weight) {
500 -> R.font.inter_medium_500
600 -> R.font.inter_semi_bold_600
700 -> R.font.inter_bold_700
800 -> R.font.inter_extra_bold_800
900 -> R.font.inter_display_black_900
else -> R.font.inter_regular_400
}
var typeface = ResourcesCompat.getFont(context, resId)
if (italic && typeface != null) {
typeface = Typeface.create(typeface, Typeface.ITALIC)
}
cache[key] = typeface
return typeface
}
}
使用
(可选项)可以在Application里面对字体包进行提前加载,调用FontCache.init(this)即可
<com.xxx.xxx.widget.MyFontTextView
android:textFontWeight="600"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:includeFontPadding="false"
android:textColor="@color/white"
android:textSize="14sp"
tools:text="Level 1 Club" />
扩展函数
fun TextView.setInterWeight(weight: Int, italic: Boolean = false) {
val newTypeface = FontCache.getInterTypeface(context, weight, italic)
if (this.typeface != newTypeface) {
this.typeface = newTypeface
}
}