首页 > 解决方案 > 如何在 Android 中使用数据绑定布局将字体系列设置为编辑文本

问题描述

我为我的活动创建一个数据模型,如下所示:

data class ActivityModel (
    var font: Int
)

并以这种方式在活动中将值设置为此字体:

items.font = R.font.san_francisco

最后,像这样在 XML 布局中使用它:

android:fontFamily="@{ResourcesCompat.getFont(context, items.font)}"

我也将此变量导入 XML 布局:

    <import type="androidx.core.content.ContextCompat"/>
    <import type="androidx.core.content.res.ResourcesCompat"/>

但是通过这种方式,应用程序不会构建,并且我从java(生成)目录中遇到错误。

那么,如何将字体系列设置为编辑文本?

标签: androiddata-binding

解决方案


您可以使用绑定适配器执行此操作,如下所示:

1-将字体类型创建为枚举类以包含所有字体:

enum class FontsTypes(@FontRes val fontRes: Int) {
    CAIRO_REGULAR(R.font.font_cairo_regular),
    CAIRO_BOLD(R.font.font_cairo_bold),
    CAIRO_SEMI_BOLD(R.font.font_cairo_semi_bold)
}

2-创建一个绑定适配器乐趣:

@BindingAdapter("font")
fun TextView.font( type: FontsTypes) {
    try {
        typeface = ResourcesCompat.getFont(context, type.fontRes)
    } catch (e: Exception) {
        e.printStackTrace()
    }
}

3- 在 xml 中导入 FontsTypes :

<data>      
  <import type="<replace_with_path>.FontsTypes"/>
</data>

4-从 xml 调用它:

    <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            font="@{model.selected ? FontsTypes.CAIRO_BOLD : FontsTypes.CAIRO_SEMI_BOLD }" />

推荐阅读