我在主题中定义了自定义文本外观。我的主题看起来像这样
<style name="Theme.MyApp" parent="Theme.MaterialComponents.Light">
.....
<item name="textAppearanceHeadline3">@style/TextAppearance.MySpark.Headline3</item>
.....
</style>
Run Code Online (Sandbox Code Playgroud)
这是风格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>
Run Code Online (Sandbox Code Playgroud)
适用于 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"/>
Run Code Online (Sandbox Code Playgroud)
适用于以编程方式引用样式
textView.setTextAppearance(R.style.TextAppearance_MyApp_Headline3)
Run Code Online (Sandbox Code Playgroud)
不起作用 当我想使用 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
Run Code Online (Sandbox Code Playgroud)
文本外观只是一种常规样式,在应用于文本视图时具有更高的优先级,并且仅使用文本属性。这就是我链接 TextView 源代码时想要显示的内容。
当您将资源 ID 传递给 时setTextAppearance,TextView 会解析TextAppearancestyleable 中的所有属性值(基本上是属性列表),将这些值存储在 TypedArray 中,然后读取并应用它们。
像我首先建议的那样使用resolveAttribute与使用类似obtainStyledAttributes,但 TypedValue 会自动设置为属性值(在本例中为资源 ID),而无需调用getResourceId。