[英]Unable to get theme attribute from BroadcastReceiver's context
I am trying to get ?colorSecondary
in my BroadcastReceiver
, so that I can set colour to notification icon and action text.我试图在我的
BroadcastReceiver
获取?colorSecondary
,以便我可以将颜色设置为通知图标和操作文本。 I am using following method to get value of my R.attr.colorSecondary
from my current theme.我正在使用以下方法从当前主题中获取
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);
Now the problem is, I am getting false
result from resolveAttribute()
call.现在的问题是,我从
resolveAttribute()
调用中得到false
结果。 Looks like the context provided by BroadcastReceiver
is not able to find colorSecondary
.看起来
BroadcastReceiver
提供的上下文无法找到colorSecondary
。 How to get the desired attribute from BroadcastReceiver
's context?如何从
BroadcastReceiver
的上下文中获取所需的属性?
Unlike Activity, BroadcastReceiver
does not provide context with a theme, as it is a non-UI context.与 Activity 不同,
BroadcastReceiver
不提供主题上下文,因为它是非 UI 上下文。 So, attributes of activity's theme are not available here.因此,此处不提供活动主题的属性。 You can try to set the theme manually to this context, as follows, to get
colorSecondary
:您可以尝试将主题手动设置为此上下文,如下所示,以获取
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.