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();
但是这不起作用
# 1 楼答案
不是
android.R.attr.colorPrimary
,而是R.attr.colorPrimary
android
前缀表示希望获取内置值,例如android:colorPrimary
您正在使用compat-lib(可能是AndroidX),它向较旧的系统版本提供较新的属性,因此这些参数实际上是“自定义”的,没有
android:
前缀# 2 楼答案
对于科特林:
对于Java: