Android R.attr.colorPrimary的预期颜色类型资源

Android R.attr.colorPrimary的预期颜色类型资源,android,android-layout,colors,attr,Android,Android Layout,Colors,Attr,我只想以编程方式设置contentScrim。所以我试过了 int color = ContextCompat.getColor(getActivity(), R.attr.colorPrimary); collapsingToolbarLayout.setContentScrimColor(color); 然后我试着 collapsingToolbarLayout.setContentScrimColor( getResources().getColor(R.attr.col

我只想以编程方式设置contentScrim。所以我试过了

int color = ContextCompat.getColor(getActivity(), R.attr.colorPrimary);
collapsingToolbarLayout.setContentScrimColor(color);
然后我试着

collapsingToolbarLayout.setContentScrimColor(
        getResources().getColor(R.attr.colorPrimary));
但我不断收到关于
R.attr.colorPrimary
的投诉。有什么帮助吗

似乎有人问过这个问题。但我所尝试的正是他们建议我应该尝试的。我的目标是minSDK 16

顺便说一句,我不能使用
R.color.colorPrimary
,因为我希望动态设置的主题不是一些硬编码/默认颜色。

尝试以下方法:

TypedValue typedValue = new TypedValue();
context.getTheme().resolveAttribute(R.attr.colorPrimary, typedValue, true);
int color = typedValue.data;

collapsingToolbarLayout.setContentScrimColor(color);
我在折叠工具栏布局文档中发现,setContentScrimColor获取颜色而不是资源id

public int getColor(Context context, int colorResId) {

    //return ContextCompat.getColor(context, colorResId); // Doesn't seem to work for R.attr.colorPrimary

    TypedValue typedValue = new TypedValue();
    TypedArray typedArray = context.obtainStyledAttributes(typedValue.data, new int[] {colorResId});
    int color = typedArray.getColor(0, 0);
    typedArray.recycle();
    return color;

}
用法:

int actualPrimaryColor=getColor(上下文,R.attr.colorPrimary)