Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why getTheme doesn't work well on Application

Tags:

android

I realize, for Context.getTheme(), it usually doesn't work well if we use Application as the Context

MyApplication.singletonInstance().getTheme().resolveAttribute(R.attr.actionBarDeleteIcon, typedValue, true);
// typedValue.resourceId will be 0x0, which is invalid

However, if I use Activity as context, it works well

MyFragment.this.getActivity().getTheme().resolveAttribute(R.attr.actionBarDeleteIcon, typedValue, true);
// typedValue.resourceId is valid

I was wondering why we cannot resolve attribute through Application?

In manifest, we specific theme information is found at Application level. So, I thought getting theme from Application object does make sense.

<application
    android:theme="..."
like image 748
Cheok Yan Cheng Avatar asked Apr 04 '13 07:04

Cheok Yan Cheng


1 Answers

It doesn't work because apparently the object returned by getApplicationContext() isn't a complete Context object, as noted in this answer by CommonsWare:

It's not a complete Context, supporting everything that Activity does. Various things you will try to do with this Context will fail, mostly related to the GUI.

One potential solution is to manually set the theme on that Context, like this:

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

But this method is not endorsed by the Android dev team; the correct solution is to use Activity for things related to the UI, like getTheme().

like image 131
seand Avatar answered Sep 29 '22 08:09

seand