简体   繁体   中英

Get Theme Attribute from Application Class

I have been using a method to obtain color attributes from the current Context :

public static int getColorAttribute(Context context, @AttrRes int attr) {
    final TypedValue value = new TypedValue();
    context.getTheme().resolveAttribute(attr, value, true);
    return value.data;
}

It works perfectly, but when I tried using it in my class that extends Application it returns 0 . In most cases I would call the method like so:

int colorAccent = Util.getColorAttribute(this, R.attr.colorAccent);

This would return the "colorAccent" that I set in themes.xml as my AppTheme in my Manifest. But in the Application class I had to call getApplicationContext() instead of this . So I switched one of my other instances of the method in an Activity to getApplicationContext() as well and it returned 0 . I also tried getApplication() and getBaseContext() with the same result.

I was wondering if there is a way to get a color from the application theme in the Application class. Or if not, why getApplicationContext().getTheme() does not seem to return the application theme.

Can you try to set the theme yourself?

getApplicationContext().getTheme().applyStyle(R.style.someTheme, true);

and then in styles have your theme that is a child of some theme you want in android. Also this method should be frowned on as themes are meant to be accessed from activity context. application context is not complete for UI tasks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM