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

huangapple go评论73阅读模式
英文:

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.

    &lt;style name=&quot;ThemePurple&quot; parent=&quot;AppTheme.NoActionBar&quot;&gt;
        &lt;item name=&quot;colorPrimary&quot;&gt;@color/colorPurple&lt;/item&gt;
        &lt;item name=&quot;colorPrimaryDark&quot;&gt;@color/colorPurpleDark&lt;/item&gt;
        &lt;item name=&quot;colorAccent&quot;&gt;@color/colorPurpleAccent&lt;/item&gt;
    &lt;/style&gt;

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>



huangapple
  • 本文由 发表于 2020年10月14日 19:39:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/64352455.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定