I'm trying to set the theme for a fragment.

Setting the theme in the manifest does not work:

android:theme="@android:style/Theme.Holo.Light"

From looking at previous blogs, it appears as though I have to use a ContextThemeWrapper. Can anyone refer me to a coded example? I can't find anything.


Setting Theme in manifest is usually used for Activity.

If you want to set Theme for Fragment, add next code in the onCreateView() of the Fragment:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    // create ContextThemeWrapper from the original Activity Context with the custom theme
    final Context contextThemeWrapper = new ContextThemeWrapper(getActivity(), R.style.yourCustomTheme);

    // clone the inflater using the ContextThemeWrapper
    LayoutInflater localInflater = inflater.cloneInContext(contextThemeWrapper);

    // inflate the layout using the cloned inflater, not default inflater
    return localInflater.inflate(R.layout.yourLayout, container, false);
}

Fragment takes its theme from its Activity. Each fragment gets assigned the theme of the Activity in which it exists.

The theme is applied in Fragment.onCreateView method, where your code creates views, which are actually objects where theme is used.

In Fragment.onCreateView you get LayoutInflater parameter, which inflates views, and it holds Context used for theme, actually this is the Activity. So your inflated views use Activity's theme.

To override theme, you may call LayoutInflater.cloneInContext, which mentions in Docs that it may be used for changing theme. You may use ContextThemeWrapper here. Then use cloned inflater to create fragment's views.