Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/227.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Android中设置字体族以使用数据绑定布局编辑文本_Android_Data Binding - Fatal编程技术网

如何在Android中设置字体族以使用数据绑定布局编辑文本

如何在Android中设置字体族以使用数据绑定布局编辑文本,android,data-binding,Android,Data Binding,我为我的活动创建如下数据模型: data class ActivityModel ( var font: Int ) android:fontFamily="@{ResourcesCompat.getFont(context, items.font)}" 并在活动中将值设置为该字体,如下所示: items.font = R.font.san_francisco 最后,在XML布局中使用它,如下所示: data class ActivityModel (

我为我的活动创建如下数据模型:

data class ActivityModel (
    var font: Int
)
android:fontFamily="@{ResourcesCompat.getFont(context, items.font)}"
并在活动中将值设置为该字体,如下所示:

items.font = R.font.san_francisco
最后,在XML布局中使用它,如下所示:

data class ActivityModel (
    var font: Int
)
android:fontFamily="@{ResourcesCompat.getFont(context, items.font)}"
我还将此变量导入XML布局:

    <import type="androidx.core.content.ContextCompat"/>
    <import type="androidx.core.content.res.ResourcesCompat"/>
但通过这种方式,应用程序无法构建,我从java生成的目录中发现了错误


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

您可以使用绑定适配器进行编辑,如下所示:

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 }" />