I'm trying to set the theme of my Activity during runtime, choosing one of a number of themes. I want the chosen theme to display immediately on startup of the Activity.
In the <application>
part of my manifest I have set a default theme with android:theme="@style/AppTheme"
. And then in my onCreate()
I use setTheme(R.style.DarkAppTheme)
to set the theme to a user-selected theme (replacing DarkAppTheme
with the selected theme).
And based on research it seems that setTheme()
should go before onCreate()
and before setContentView()
, which I do.
BUT although this works to display the Activity in the user selected theme, the Activity first loads with what looks like the default theme, and then after a short delay the correct theme loads.
If I set the user selected theme directly in the manifest, that loads immediately as I want, but of course that is hardcoded and I want to change this dynamically based on a shared preference.
How do I avoid the visible changeover? I want the user selected theme to be displayed right from the start.
Thanks.
In Android Studio, open themes. xml (app > res > values > themes > themes. xml). Notice the theme name, Theme.
The Activity first loads with what looks like the default theme, and then after a short delay the correct theme loads... How do I avoid the visible changeover?
There are 2 parts to an Activity 'Enter/Opening' window animation, when your app is first launched from the icon on the Home Screen:
Part 1 is what you identified as "what looks like the default theme". You can disable this first part with the following item in your Activity/App style:
<item name="android:windowDisablePreview">true</item>
This will prevent the 'dark gray rectangle appear' animation, and only allow the 'reveal of the view layout', to therefore avoid the visible changeover or flicker. But there are caveats:
Documentation of windowDisablePreview
:
Flag allowing you to disable the splash screen for a window. The default value is false; if set to true, the system can never use the window's theme to show a splash screen preview before your actual instance is shown to the user.
Further info:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With