Set theme for a Fragment Set theme for a Fragment android android

Set theme for a Fragment


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:

@Overridepublic 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.


For applying a single style I've used just

getContext().getTheme().applyStyle(styleId, true);

in onCreateView() of the fragment before inflating root view of the fragment and it works for me.