如何在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 }" />