简体   繁体   English

如何从代码中检索和使用样式属性?

[英]How to retrive and use a style attribute from code?

I have defined a theme in style.xml file.我在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>

I want to use the colorPrimary of this theme to a textView in a recyclerView .我想用colorPrimary这个主题的一个textViewrecyclerView 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..但这不起作用..

not android.R.attr.colorPrimary , but just R.attr.colorPrimary不是android.R.attr.colorPrimary ,而只是R.attr.colorPrimary

android prefix means you want to get built-in value, eg android:colorPrimary android前缀意味着你想获得内置值,例如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您正在使用 compat lib(可能是 AndroidX),它为旧系统版本提供更新的属性,因此这些参数实际上是“自定义”,没有android:前缀

For Kotlin :对于科特林

val typedValue = TypedValue()
context.theme.resolveAttribute(android.R.attr.colorPrimary, typedValue, true)
holder.titleView.setTextColor(typedValue.data)

For Java:对于Java:

TypedValue typedValue = new TypedValue();
context.getTheme().resolveAttribute(android.R.attr.colorPrimary, typedValue, true);
holder.titleView.setTextColor(typedValue.data);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM