微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

带有主题风格的 TextAppearanceSpan

如何解决带有主题风格的 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.textAppearanceHeadline4R.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)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。