问题描述
我只想以编程方式设置contentScrim.所以我尝试了
I just want to set contentScrim programmatically. So I tried
int color = ContextCompat.getColor(getActivity(), R.attr.colorPrimary);
collapsingToolbarLayout.setContentScrimColor(color);
然后我尝试了
collapsingToolbarLayout.setContentScrimColor(
getResources().getColor(R.attr.colorPrimary));
但是我不断收到有关 R.attr.colorPrimary
的投诉.有什么帮助吗?
But I keep getting complaints about R.attr.colorPrimary
. Any help with this?
有人似乎问了这个问题Android-应该在此处传递解析后的颜色而不是资源ID:`getResources().getColor(R.attr.colorPrimary)`.但是我尝试的正是他们建议我尝试的方法.我的目标是minSDK 16.
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.
顺便说一句,我不能使用 R.color.colorPrimary
,因为我希望动态设置的主题不是某种硬编码/默认颜色.
BTW I cannot use R.color.colorPrimary
because I want the dynamically set theme not some hardcoded/default color.
推荐答案
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(context,R.attr.colorPrimary);
这篇关于R.attr.colorPrimary的color类型的预期资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!