I am working in an Android app built with MAUI. In the application settings there is the possibility of changing between light/dark MAUI themes, however, when looking at how the interface looks I realized that something was not quite right, for example in the “dark” configuration the buttons with a white background do not present the “visual effect” when clicked.
I discovered that this is associated with the fact that on the one hand there are the MAUI themes, but there are also the native Android ones, which are quite similar in terms of operation (night mode activated/deactivated). These native Android themes influence, for example, the colors of the “alert displays”, the background of the “picker control” and the animation of the buttons when clicked.
There is a way to switch between night mode on/off programmatically, but the changes are not fully reflected until the app has been restarted. Here’s how I currently switch between themes in my app:
internal static void ChangeAppTheme(int selectedThemeIndex)
{
switch (selectedThemeIndex)
{
case 0: App.Current.UserAppTheme = AppTheme.Unspecified; break;
case 1: App.Current.UserAppTheme = AppTheme.Dark; break;
case 2: App.Current.UserAppTheme = AppTheme.Light; break;
}
#if ANDROID
AndroidX.AppCompat.App.AppCompatDelegate.DefaultNightMode = App.Current.UserAppTheme switch
{
AppTheme.Light => AndroidX.AppCompat.App.AppCompatDelegate.ModeNightNo,
AppTheme.Dark => AndroidX.AppCompat.App.AppCompatDelegate.ModeNightYes,
_ => AndroidX.AppCompat.App.AppCompatDelegate.ModeNightFollowSystem
};
endif
}
Investigating more I understood that it is necessary to “recreate” the “Android main activity” so that all the changes take effect correctly, this is achieved with the following line
Platform.CurrentActivity.Recreate();
The changes are applied correctly when doing this from the main window in an empty application, however when doing this from my settings page I get the following error:
Java.Lang.IllegalArgumentException: 'You cannot start a load for a destroyed activity'
Does anyone have any idea if it is possible to do this and how? I apologize in advance for my level of English :D.
I tried to do the Platform.CurrentActivity.Recreate();
from a Dispatcher=>Dispatch action but not working
Eric Rojas is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.