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="..."
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 thatActivitydoes. Various things you will try to do with thisContextwill 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().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With