Java – Change fragment Change theme

Change fragment Change theme… here is a solution to the problem.

Change fragment Change theme

I

need to change the fragment theme dynamically, I tried this code, but it doesn’t work with onCreate or onCreateView().

getActivity().setTheme(R.style.ActionMode);

How do I set a theme from fragment?

Solution

In the onCreateView() method, you must create a ContextThemeWrapper and extend the theme style from it, as follows:

@Override
public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
    create ContextThemeWrapper from the original Activity Context with the custom theme
    Context context = new ContextThemeWrapper(getActivity(), R.style.your_Custom_Theme);
    clone the inflater using the ContextThemeWrapper
    LayoutInflater localInflater = inflater.cloneInContext(context);
    inflate using the cloned inflater, not the passed in default
    return localInflater.inflate(R.layout.your_layout, container, false);
}

Related Problems and Solutions