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.

Leave a Comment