

This is pretty straight forward, however this works when an activity is first created and has no effect on the current open Activity or any backgrounded Activities. Changing the theme is fairly straight forward, something like below should do it: setTheme(darkTheme ? R.style. Changing the theme at runtimeĪs mentioned before, it’s only possible to change the theme of an Activity in the `onCreate` method and that to only before `super` has been called. I've provided an example implementation of each of these methods below. Neither of these options is ideal, you may even want to consider a hybrid of these two approaches. This way, when the theme is changed, you can loop through all the Views again and change the attributes to reflect the new theme. So our second option is to recursively loop through all of our views and set their attributes each time an Activity or Fragment is created. This is problematic because it’s hard to provide a seamless experience to the user if you have to restart the app or Activity in order to change the theme. That being said, it is possible to change the theme of an Activity, however only in the`onCreate` method and only before `super` is called. The use case is often that there is a setting, button or check box which can switch between different colour themes or between something like day and night mode.Įvery time such a requirement comes up, the first thing a quick Google search shows is that it’s not possible to change themes at runtime. Public class ButtonActivity extends AppCompatActivity implements View.Every so often, I see a question posted on StackOverflow which is effectively asks how to change the themes of an app at runtime.

The first two buttons are added in the layout XML file.

