读取文本外观属性

Mar*_*cci 3 android android-view android-styles

I\xc2\xb4m 尝试从样式中读取属性TextAppearance,因此我可以将这些值应用于重要的组件(TextPaint例如)\n理想情况下,I\xc2\xb4d 喜欢接收引用 TextAppearance 的样式 id 并读取文本颜色等值,字体等

\n\n

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

\n\n

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

\n\n

谢谢!

\n

Nic*_*las 6

如果您使用 Google Material Components,它们有一个非常有用的TextAppearance类。它是受限制的 API,但你可以忽略它:

@SuppressLint("RestrictedApi")
val textAppearance = TextAppearance(context, R.style.TextAppearance_MaterialComponents_Body1)
Run Code Online (Sandbox Code Playgroud)

您需要的所有属性都可以作为类的成员直接使用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...
Run Code Online (Sandbox Code Playgroud)

还有一些技巧可以在所有 API 级别上正确地增加颜色资源,并且获取字体并不是很简单。如果需要,您可以查看代码:TextAppearance.java