How to change theme using program code

I want to use two different themes for my page. so how can I do that? I want two buttons and each button will switch to new theme in same way we change wallpapers. please help me.


This is a good question and I don’t know if it’s documented anywhere very well. There was
this discussion
about multiple themes earlier, which explained some technical aspects why changing themes is not supported in Vaadin 7.

There’s several very different cases for supporting multiple themes, depending on the page structure and the phase where the theme is selected.


If the theme can be created when the UI is loaded, such as if you determine the theme from a cookie (for the user) or from the URL, you can do it with a custom UIProvider that sets the theme in the UI.

If you want to use the above method when changing the theme in a UI, you can store the theme name in the session, order a page reload with Page.getCurrent().reload(), and then apply the theme in the UIProvider when recreating the UI. The reload is, of course, annoying.

If you are embedding multiple UIs to a single page, they can have different themes if you have wrapped them in a selector with the theme name in the styles.scss, as is recommended.

Sometimes it may be easiest to inject some user-specific CSS rules with Page.getCurrent().getStyles().add(). However, removing those requires a page reload.

If you really really want to have multiple complete themes in the same page and switch between dynamically, you can define a Sass theme as is done
in this example
. However, the base theme gets compiled in into each of the sub-themes, so the compilation takes more time and the resulting CSS file is bigger. Just having two themes doubles the CSS size.

[/list]However, usually in perhaps most cases, you can avoid the need for multiple themes by designing your rules so that simply changing a top-level style name changes the overall appearance. For example, use UI.getCurrent().setStyleName(“administrator”) and then have CSS rule such as “.v-ui.administrator {background: red}”.

Thank you…
Marko Grönroos
I should try another way then. :slight_smile:

You might be happy to learn that we added setTheme functionality to Vaadin 7.3.0.

See for a very simple example on how this is used.