【问题标题】:How to retrive and use a style attribute from code?如何从代码中检索和使用样式属性?
【发布时间】:2020-10-14 11:39:54
【问题描述】:

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

但这不起作用..

【问题讨论】:

    标签: java android styles android-theme


    【解决方案1】:

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

    android 前缀表示您想要获取内置值,例如android:colorPrimary

    您使用的是兼容库(可能是 AndroidX),它为旧系统版本提供了更新的属性,所以这些参数实际上是“自定义”的,没有 android: 前缀

    【讨论】:

      【解决方案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);
      

      【讨论】:

        猜你喜欢
        • 2012-11-23
        • 2016-11-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-12-08
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多