android - 带有主题样式的 TextAppearanceSpan
问题描述
TL;DR 如何使用当前主题的样式与TextAppearanceSpan?
假设我正在为我的应用程序使用自定义样式,并为 Subtitle1 使用自定义样式,如下所示:
<style name="MyAppTheme" parent="Theme.MaterialComponents">
<item name="textAppearanceSubtitle1">@style/MyStyle.TextAppearanceSubtitle1</item>
</style>
我的主题不过是
<style name="MyStyle.TextAppearanceSubtitle1" parent="TextAppearance.MaterialComponents.Subtitle1">
<item name="textSize">16sp</item>
</style>
现在我想用这种自定义样式构建一个 SpannedString,所以我使用的是TextAppearanceSpan
val apperSpan = TextAppearanceSpan(context, R.attr.TextAppearanceSubtitle1)
println("Your style has textSize = ${apperSpan.textSize}")
但在这种情况下,输出是Your style has textSize = -1
. R.attr.textAppearanceHeadline4
但是,如果我与交换R.style.MyStyle_TextAppearanceSubtitle1
,textSize 将是正确的,但这不是独立于主题的。
如何从当前主题中提取具有样式的TextAppearanceSpan ?
解决方案
您只需将样式/外观资源 id传递给TextAppearanceSpan
构造函数,而不是属性 id。要从当前主题解析属性值,请使用Theme#resolveAttribute方法:
val outValue = TypedValue()
context.theme.resolveAttribute(R.attr.TextAppearanceSubtitle1, outValue, true)
val appearance = outValue.resourceId
//...
val apperSpan = TextAppearanceSpan(context, appearance)
或者
val typedArray = context.obtainStyledAttributes(intArrayOf(R.attr.TextAppearanceSubtitle1))
val appearance = typedArray.getResourceId(0, 0)
typedArray.recycle()
//...
val apperSpan = TextAppearanceSpan(this, appearance)
推荐阅读
- git - npm 将本地模块链接到特定分支
- html - 为什么我的背景图片没有纵向扩展
- delphi - 用鼠标正确移动旋转图形
- react-native - react native--无法修复意外的 TypeError(见屏幕截图)
- php - 当前用户和 env 用户在通过 php 和 apache 执行 shell 脚本时不匹配
- windows - Windows批处理脚本:提示后if语句不一致
- python - 为分类特征列指定形状?
- c++ - 具有自定义构造函数的类型的动态数组分配 (C++)
- ios - Is this possible to Set ViewController Storyboard ID programmatically?
- r - 理解 foreach