【问题标题】:Read text appearance attributes读取文本外观属性
【发布时间】:2020-05-17 00:50:28
【问题描述】:
我正在尝试从TextAppearance 样式中读取属性,因此我可以将这些值应用于非平凡组件(例如TextPaint)
理想情况下,我希望收到一个引用 TextAppearance 的样式 ID,并读取文本颜色、字体等值。
我注意到 R.styleable.TextAppearance 和 TextAppearanceAttributes 类是内部的,因此无法访问。
这个想法有替代方案吗?
谢谢!
【问题讨论】:
标签:
android
android-view
android-styles
【解决方案1】:
如果您使用 Google Material Components,它们有一个非常有用的 TextAppearance 类。它是受限制的 API,但您可以忽略它:
@SuppressLint("RestrictedApi")
val textAppearance = TextAppearance(context, R.style.TextAppearance_MaterialComponents_Body1)
您需要的所有属性都可以作为TextAppearance 类的成员直接使用。
如果这不是一个选项,那么您可以随时复制他们使用的代码。基本上它涉及使用R.styleable.TextAppearance 数组及其来自R.styleable.TextAppearance_android_** 的索引获取样式属性(这些是私有的,并且是greylist 的一部分):
TypedArray a = context.obtainStyledAttributes(id, R.styleable.TextAppearance);
textSize = a.getDimension(R.styleable.TextAppearance_android_textSize, 0f);
textStyle = a.getInt(R.styleable.TextAppearance_android_textStyle, Typeface.NORMAL);
// Other attributes are obtained similarly...
还有一些技巧可以在所有 API 级别上正确填充颜色资源,并且获取字体并不是很简单。如果需要,可以查看代码:TextAppearance.java。