读取文本外观属性

Read text appearance attributes

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

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

这个想法有替代方案吗?

谢谢!

如果您使用 Google Material 组件,它们将非常有用 TextAppearance class。它受到限制 API,但您可以忽略它:

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

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

如果那不是一个选项,那么您可以随时复制他们使用的代码。基本上它涉及使用 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.