Android - Fragment specific theme

   Few applications might want to apply specific theme for Fragments and this could be easily achieved as long as the Fragment views are recreated when moving across the back stack. This is the case when Fragments are replaced rather than being added ( FragmentTransaction.replace ). The views corresponding to a replaced fragment in back stack would need to created again and added as child of the fragment container. So all that is needed is a layout inflater based on the desired theme and the quick trick is to set the theme before committing the fragment transaction.


    private void next(int nextThemeResId, Fragment fragment, String tag, int containerViewId) {
        setTheme( nextThemeResId );
        FragmentTransaction transaction = getFragmentManager().beginTransaction();
        transaction.replace(containerViewId, fragment, tag);
        transaction.addToBackStack(null);
        transaction.commit();
    }

    private void previous(int prevThemeResId)
    {
        setTheme( prevThemeResId );
        getFragmentManager().popBackStack();
    }


  The documentation of setTheme() could be misleading. It simply states that it should be invoked before any views are instantiated in the Context (for example before calling setContentView(View) or inflate(int, ViewGroup)). It doesn't clarify as to what happens when the setContentView(View) is invoked again. However, in case of Fragment activities setContentView() is often invoked to create the fragment container view and yet changing the theme at run time works.

   The new theme is effective as soon as it is set and it doesn't reinflate existing views created via setContentView() and the documentation is to warn about this scenario. However, any new views created using the activity context (which now uses the new theme) would be based on the new theme. This helps with Fragments as Fragment's views are created on demand via onCreateView() callback and solves the purpose of Fragment specific theme. The only catch being developers should set appropriate theme as and when the Fragment is added and removed from the back stack.

1 comment:

Rakshit said...

Is there any way to do it from style or XML?