簡體   English   中英

如何以編程方式在 TextView 上設置 ?android:attr/textAppearanceListItem

[英]How to programatically set ?android:attr/textAppearanceListItem on a TextView

我正在嘗試設置導航抽屜中自定義適配器中的文本視圖的文本外觀。 我想讓一些項目的文本比其他項目的文本小(比如谷歌音樂的導航抽屜)。 所以我在 getView 方法中有一個 if 語句,我想對列表項使用默認的 android 樣式。

我知道我可以做到以下幾點:

textView.setTextAppearance(getContext(), android.R.style.TextAppearance_Small);

但是我找不到您可以在 xml 中設置的 textAppearanceListItem 屬性的 android.R.style 值:

android:textAppearance="?android:attr/textAppearanceListItem"

以下代碼適用於我:

textView.setTextAppearance(getContext(), android.R.attr.textAppearanceListItem);

setTextAppearance需要@StyleRes int resId ,而android.R.attr.textAppearanceListItem是一個attr ,所以它不起作用。

查看 Android 框架源代碼,樣式因應用主題而異。 例如在材質主題中,它被定義為@style/TextAppearance.Material.ListItem

https://android.googlesource.com/platform/frameworks/base/+/refs/tags/android-11.0.0_r48/core/res/res/values/themes_material.xml#124

該樣式定義為TextAppearance.Material.Subhead

https://android.googlesource.com/platform/frameworks/base/+/refs/tags/android-11.0.0_r48/core/res/res/values/styles_material.xml#498


因此,一種解決方案是直接使用該樣式值:

textView.setTextAppearance(android.R.style.TextAppearance_Material_Subhead);

或者您可能想根據當前主題解析它的值,這可能更詳細:

TypedValue value = new TypedValue();
context.getTheme().resolveAttribute(android.R.attr.textAppearanceListItem, value, true);
textView.setTextAppearance(value.resourceId);

如果使用 kotlin, splitties-resources更方便:

textView.textAppearance = context.resolveThemeAttribute(android.R.attr.textAppearanceListItem)

在此處閱讀其文檔: https : //github.com/LouisCAD/Splitties/blob/v3.0.0/modules/resources/README.md

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM