androidandroid-fragments

change the background color of the application from a fragment


I am currently using an architecture where I have multiple fragments that I swap in the same activity.
I need to be able to use a different background color for one of these fragments BUT I don't want to use the lazy solution that adds one layer of overdraw.
For clarity : I have a window background setted by my theme and on top of it I draw cards & lists. In one of my fragments I need a slightly different window background color.
Is there any way to do that ? I already tried to use a ContextThemeWrapper but it does not seem to work (maybe because the background has already been drawed ?)

Thanks in advance for your help.


Solution

  • Just found it :

    It is doable by calling

        ColorDrawable cd = new ColorDrawable(getActivity().getResources().getColor(
                    R.color.your_color));
    
        getActivity().getWindow().setBackgroundDrawable(cd);
    

    during the initialization of your fragment, when it is attached to the activity.