Theme/Style is not applied when inflater used with ApplicationContext

Solution # 1

The inflate method accepts optional 'ViewGroup root' argument:

public View inflate (int resource, ViewGroup root, boolean attachToRoot)

If we have value to pass as 'root' parameter, than hence we can use it to get 'activity context' from where we can get correct LayoutInflater:

ViewGroup root > activity context > LayoutInflater

So my code could be:

private void add(LinearLayout container) {
    LayoutInflater inflater = getInflater(container.getContext());
    inflater.inflate(R.layout.my_template, container, true);
}

Solution # 2

Just tried to set Application Context theme programmatically, and it works:

getApplicationContext().setTheme(R.style.MyTheme);

I think it was logical to expect this markup:

<application 
    android:icon="@drawable/icon" 
    android:label="@string/app_name"
    android:theme="@style/MyTheme"
    >

to set it automatically, but it does not.


Never use an Application Context to inflate views, because styling doesn't work with this context. Always use an Activity's context when playing with views. The only exception is when you need to create RemoteViews from a Service.

More info about the different types of Contexts and their capabilities can be found in this excellent article.


You probably use a context that isn't one that has a theme.

To solve it, use something as such:

val inflater= LayoutInflater.from(context).cloneInContext(ContextThemeWrapper(context, R.style.some_activity_theme))

You can read more about this here