0

I'm trying to set a theme for a fragment within an activity.

When I set the fragment theme in the onCreate function of the fragment using the inflator as described in Set a theme for a fragment like this:

    var contextThemeWrapper = ContextThemeWrapper(getActivity(), R.style.FragmentTheme);
    var localInflater = inflater.cloneInContext(contextThemeWrapper)
    return localInflater.inflate(R.layout.fragment_component_indicator, container, false)

or in the layout of the fragment XML, the theme for the fragment does not take effect.

Using the Layout Inspector, I see that the theme does get added to the fragment layout but the activity theme is still there:

enter image description here

Any tips on how I can set the theme of the fragment?

Thank you.

Mycoola
  • 1,135
  • 1
  • 8
  • 29
PastAndSalmon
  • 175
  • 2
  • 11
  • did you try to add this code in onCreateView ? – Mycoola Aug 21 '18 at 10:50
  • yes, i tried it in the onCrreateView of the fragment. – PastAndSalmon Aug 21 '18 at 11:23
  • So they are both applied. This is how I'd expect it to work. Now you fragment theme should just override the styles and everything should work as expected. Correct me if I'm wrong. Also it be nice to know why you want to do this as we might be able to suggest an alternative approach... – Warpzit Aug 22 '18 at 11:00

1 Answers1

0

You can try to override context theme in Fragment.onGetLayoutInflater() method. This is place where fragment view is not inflated yet.

override fun onGetLayoutInflater(savedInstanceState: Bundle?): LayoutInflater {
    context?.setTheme(R.style.Theme_AppName_Light)
    return super.onGetLayoutInflater(savedInstanceState)
}
pratt
  • 1,534
  • 14
  • 17