英文:
How to retrive and use a style attribute from code?
问题
我在style.xml
文件中定义了一个主题。
<style name="ThemePurple" parent="AppTheme.NoActionBar">
<item name="colorPrimary">@color/colorPurple</item>
<item name="colorPrimaryDark">@color/colorPurpleDark</item>
<item name="colorAccent">@color/colorPurpleAccent</item>
</style>
我想要将这个主题的colorPrimary
应用到recyclerView
中的一个textView
。我尝试了以下方法:
int[] attrs = {android.R.attr.colorPrimary};
TypedArray typedArray = mContext.obtainStyledAttributes(R.style.ThemePurple, attrs);
holder.titleView.setTextColor(typedArray.getColor(0, Color.BLACK));
typedArray.recycle();
但这并没有起作用。
英文:
I have defined a theme in style.xml
file.
<style name="ThemePurple" parent="AppTheme.NoActionBar">
<item name="colorPrimary">@color/colorPurple</item>
<item name="colorPrimaryDark">@color/colorPurpleDark</item>
<item name="colorAccent">@color/colorPurpleAccent</item>
</style>
I want to use the colorPrimary
of this theme to a textView
in a recyclerView
. I've tried this:
int[] attrs = {android.R.attr.colorPrimary};
TypedArray typedArray = mContext.obtainStyledAttributes(R.style.ThemePurple, attrs);
holder.titleView.setTextColor(typedArray.getColor(0, Color.BLACK));
typedArray.recycle();
But this is not working..
答案1
得分: 4
不是 android.R.attr.colorPrimary
,而只是 R.attr.colorPrimary
android
前缀表示您想要获取内置的值,例如 android:colorPrimary
您正在使用兼容库(可能是 AndroidX),该库会将较新的属性传递到较旧的系统版本,因此这些参数实际上是“自定义”的,不带 android:
前缀
英文:
not android.R.attr.colorPrimary
, but just R.attr.colorPrimary
android
prefix means you want to get built-in value, e.g. android:colorPrimary
you are using compat lib (AndroidX probably) which delivers newer attributes to older system versions, so these parameteres are in fact "custom", without android:
prefix
答案2
得分: 2
对于 Kotlin:
val typedValue = TypedValue()
context.theme.resolveAttribute(android.R.attr.colorPrimary, typedValue, true)
holder.titleView.setTextColor(typedValue.data)
对于 Java:
TypedValue typedValue = new TypedValue();
context.getTheme().resolveAttribute(android.R.attr.colorPrimary, typedValue, true);
holder.titleView.setTextColor(typedValue.data);
英文:
For Kotlin:
val typedValue = TypedValue()
context.theme.resolveAttribute(android.R.attr.colorPrimary, typedValue, true)
holder.titleView.setTextColor(typedValue.data)
For Java:
TypedValue typedValue = new TypedValue();
context.getTheme().resolveAttribute(android.R.attr.colorPrimary, typedValue, true);
holder.titleView.setTextColor(typedValue.data);
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论