如何从代码中检索和使用样式属性? [英] How to retrive and use a style attribute from code?

查看:221
本文介绍了如何从代码中检索和使用样式属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在 style.xml 文件中定义了一个主题.

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>

我想将此主题的 colorPrimary 用于 recyclerView 中的 textView .我已经尝试过了:

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();

但这不起作用.

推荐答案

不是 android.R.attr.colorPrimary ,而只是 R.attr.colorPrimary

android 前缀意味着您要获取内置值,例如 android:colorPrimary

android prefix means you want to get built-in value, e.g. android:colorPrimary

您正在使用compat lib(可能是AndroidX),它将较新的属性提供给较旧的系统版本,因此这些参数实际上是自定义"的,没有 android:前缀

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

这篇关于如何从代码中检索和使用样式属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆