expected resource of type color for R.attr.colorPrimary

早过忘川 提交于 2021-01-28 02:30:34

问题


I just want to set contentScrim programmatically. So I tried

int color = ContextCompat.getColor(getActivity(), R.attr.colorPrimary);
collapsingToolbarLayout.setContentScrimColor(color);

Then I tried

collapsingToolbarLayout.setContentScrimColor(
        getResources().getColor(R.attr.colorPrimary));

But I keep getting complaints about R.attr.colorPrimary. Any help with this?

Someone seems to have ask this question Android - Should pass resolved color instead of resource id here: `getResources().getColor(R.attr.colorPrimary)`. But what I tried is exactly what they suggested I should try. I am targeting minSDK 16.

BTW I cannot use R.color.colorPrimary because I want the dynamically set theme not some hardcoded/default color.


回答1:


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;

}

Usage:

int actualPrimaryColor = getColor(context, R.attr.colorPrimary);




回答2:


Try this:

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

collapsingToolbarLayout.setContentScrimColor(color);

What I found in collapsingToolbarLayout documention, setContentScrimColor get color and not resource id



来源:https://stackoverflow.com/questions/40203631/expected-resource-of-type-color-for-r-attr-colorprimary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!