读取文本外观属性



我正在尝试从TextAppearance样式中读取属性,因此我可以将值应用于非平凡组件(例如TextPaint( 理想情况下,我希望收到引用 TextLook 的样式 ID 并读取文本颜色、字体等值。

我注意到R.styleable.TextAppearance是内部的,因此无法访问,以及TextAppearanceAttributes类。

这个想法还有其他选择吗?

谢谢!

如果你使用谷歌材质组件,它们有一个非常有用的TextAppearance类。它是受限制的API,但您可以忽略它:

@SuppressLint("RestrictedApi")
val textAppearance = TextAppearance(context, R.style.TextAppearance_MaterialComponents_Body1)

您需要的所有属性都可以作为TextAppearance类的成员直接使用。

如果这不是一个选项,那么你总是可以复制他们使用的代码。基本上,它涉及使用R.styleable.TextAppearance数组及其从R.styleable.TextAppearance_android_**索引获取样式属性(这些是私有的,是灰名单的一部分(:

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

最新更新