我正在尝试在?colorSecondary
中获取BroadcastReceiver
,以便可以将颜色设置为通知图标和操作文本。我正在使用以下方法从当前主题中获取R.attr.colorSecondary
的值。
@ColorRes
public static int getAttrColorResId(Context context, @AttrRes int resId) {
TypedValue outValue = new TypedValue();
Resources.Theme theme = context.getTheme();
boolean success = theme.resolveAttribute(resId, outValue, true);
return outValue.resourceId;
}
// usage
int colorRes = getAttrColorResId(context, R.attr.colorSecondary);
现在的问题是,我正在从false
调用中获得resolveAttribute()
结果。似乎BroadcastReceiver
提供的上下文找不到colorSecondary
。如何从BroadcastReceiver
的上下文中获取所需的属性?
[与活动不同,BroadcastReceiver
不提供带有主题的上下文,因为它是非UI上下文。因此,活动主题的属性在这里不可用。您可以尝试按如下所示手动将主题设置为此上下文,以获取colorSecondary
:
@ColorRes
public static int getAttrColorResId(Context context, @AttrRes int resId) {
TypedValue outValue = new TypedValue();
Resources.Theme theme = context.getTheme();
boolean success = theme.resolveAttribute(resId, outValue, true);
// if not success, that means current call is from some non-UI context
// so set a theme and call recursively
if (!success) {
context.getTheme().applyStyle(R.style.YourTheme, false);
return getAttrColorResId(context, resId);
}
return outValue.resourceId;
}