无法从BroadcastReceiver的上下文中获取主题属性

问题描述 投票:0回答:1

我正在尝试在?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的上下文中获取所需的属性?

android broadcastreceiver android-theme
1个回答
0
投票
]获取我的R.attr.colorSecondary的值。

[与活动不同,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;
}
© www.soinside.com 2019 - 2024. All rights reserved.