android - 如何在 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(生成)目录中遇到错误。
那么,如何将字体系列设置为编辑文本?
解决方案
您可以使用绑定适配器执行此操作,如下所示:
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 }" />
推荐阅读
- java - find 200 digit prime numbers using BigInteger
- postgresql - 如何使用 Spring Boot JPA 在 Postgres 中存储几何点?
- r - 根据匹配的 2 列将行放入列表项
- api-manager - Gravitee 是否支持纯 SOAP API 集成而不转换为 REST
- python - 从 2 个 uint64 值中提取 Spooky-hash 128 位值
- r - 使用 R 并行处理 XML 节点
- javascript - 不能在 Typescript 和 Webpack 项目中使用 square/js-jose (jose-jwe-jws) npm 包
- php - Symfony 3 - 我在管理我的角色时遇到了一些困难
- powershell - 移除所有 Sitecore 节点的发布限制
- lightbox2 - 灯箱图像 X 关闭按钮 对齐图像右上角