The ability to switch theme is gaining popularity in Android applications. Here's how to implement such a switch.

There are at least two options for implementing theme change:

  • With recreating Activity / Fragment
  • Without recreating Activity / Fragment

Changing theme with recreating Activity

The essence of the approach is that when you create an Activity, all your interface elements are rendered according to the specified application theme. But you can programmatically add a different style to an application. 

All that remains is to recreate the Activity, and all the colors will automatically be repainted in the new palette. It's simple, you call setTheme() and then recreate().
An important point, if you want to set the theme directly in onCreate (), then do it before calling super


Advantages of the approach

  • Minimal intervention in the application code
  • Guaranteed consistency of appearance

Cons of the approach

  • Rebuilding complex UI can cause noticeable lags
  • If there is an element that does not restore its state, it will look like a bug

Changing theme without re-creating Activity



This approach changes the overall theme of the application and at the same time notifies the out-of-the-box interface of changes in the runtime. Every element of your screen reacts to change and redraws itself.

Handling clicking a theme change

In the GIF example, the scrollview overrides its background in the same way.



And graphs are drawn through onDraw(), Paint for which it changes color in the same way with a general change of styles


Advantages of the approach

  • No time wasted on re-creating elements
  • The UI state will be consistent (even fling in the scrollview in place)

Cons of the approach

  • You need to keep track of each element and handle the theme change for it separately