问题
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