setTextAppearance 以编程方式使用主题属性

setTextAppearance using theme attributes programmatically

我在我的主题中定义了自定义 textAppearance。我的主题看起来像这样

<style name="Theme.MyApp" parent="Theme.MaterialComponents.Light">
.....
<item name="textAppearanceHeadline3">@style/TextAppearance.MySpark.Headline3</item>
.....
</style>

这里是样式TextAppearance.MyApp.Headline3

<style name="TextAppearance.MyApp.Headline3" parent="TextAppearance.MaterialComponents.Headline3">
        <item name="fontFamily">@font/avenir_next_demi</item>
        <item name="android:textSize">40sp</item>
        <item name="android:gravity">left|top</item>
        <item name="android:textStyle">bold</item>
        <item name="android:textColor">?attr/colorOnSurface</item>
    </style>

适用于 XML

<com.google.android.material.textview.MaterialTextView
        android:textAppearance="?attr/textAppearanceHeadline3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/add_product_description"/>

WORKS 以编程方式引用样式

textView.setTextAppearance(R.style.TextAppearance_MyApp_Headline3)

不适用于 当我想使用 attr 以编程方式应用 textAppearance 时,我找不到类似这样的方法。

textView.setTextAppearance(R.attr.textAppearanceHeadline3)

我想使用 attr 来帮助我切换不同的主题。

每个 Android 资源都有一个与之关联的整数 ID。属性仅引用资源 ID,而不是资源本身。要从属性解析此资源 ID,请将 Context.obtainStyledAttributes 与属性数组一起使用:

val attrs = intArrayOf(R.attr.myTextAppearance)       // The array of attributes we're interested in.
val ta = context.obtainStyledAttributes(attrs)        // Get the value referenced by the attributes in the array
val resId = ta.getResourceId(0, 0)                    // The first 0 is the index in the 'attrs' array.
ta.recycle()                                          // Don't forget that! You can also use TypedArray.use { } extensions from android KTX.
TextViewCompat.setTextAppearance(textView, resId)     // Utility method to set text appearance for all SDK versions

text appearance只是一个普通的样式,应用在text view上有更高的优先级,只用到text属性。这就是我在链接 TextView 源代码时想要显示的内容。

当您将资源 ID 传递给 setTextAppearance 时,TextView 会解析 TextAppearance 样式(基本上是属性列表)中的所有属性值,将这些值存储在 TypedArray 中,然后读取并应用它们。

像我最初建议的那样使用 resolveAttribute 与使用 obtainStyledAttributes 类似,但 TypedValue 会自动设置为属性值,在本例中为资源 ID,而无需调用 getResourceId.