有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

我在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 = {安卓.R.attr.colorPrimary};
TypedArray typedArray = mContext.obtainStyledAttributes(R.style.ThemePurple, attrs);
holder.titleView.setTextColor(typedArray.getColor(0, Color.BLACK));
typedArray.recycle();

但是这不起作用


共 (2) 个答案

  1. # 1 楼答案

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

    android前缀表示希望获取内置值,例如android:colorPrimary

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

  2. # 2 楼答案

    对于科特林

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