SetTheme does not work when using viewBinding

763 Views Asked by At

I have two themes in my app (dark and light mode) and I could change the themes without any problem. But, since I used the viewBinding, the setTheme() function did not work and I can't change the activity's theme anymore. Does anyone know what's the problem?

This is my old code (which worked)

setTheme(getAppTheme());
setContentView(R.layout.my_layout);

And the new code (which does not work)

setTheme(getAppTheme());
setContentView(binding.getRoot());

Thank you for taking the time to read, and sorry for my bad English :)

1

There are 1 best solutions below

0
On BEST ANSWER

You must be initializing your binding variable before you're setting your theme. You have to initialize your activity binding after you've set the theme, for it to work correctly.

setTheme(getAppTheme());
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.getRoot());