Search code examples
xamarin.formsxamarin.androidxamarin.ios

How to enable OS AppTheme Dark/Light in Run time in Xamarin Forms


I am following Respond to system theme change to respond to OS theme in xamarin form app. The app supports both Dark and Light themes with AppThemeBinding. I am not using any custom themes. I am following OS themes only. So I have a Switch which the user would prefer to enable Dark Mode (same as OS). The link suggests the following code to enable specified Mode (e.g Dark Mode).

Application.Current.UserAppTheme = OSAppTheme.Dark;

The above code does nothing, but if I write the above code in App.cs after InitializeComponent() The app changes to Dark Mode.

I Then realized to restart the MainActivity in Android which I did with the help of Dependency.

[assembly: Dependency(typeof(AndroidThemeChanged))]
    public class AndroidThemeChanged : ITheme
        {
            public void OnThemeChanged()
            {
                var activity = CrossCurrentActivity.Current.Activity;
                var intent = GetLauncherActivity();
                activity.Finish();
                activity.StartActivity(intent);
            }
            public static Intent GetLauncherActivity()
            {
                var packageName = AndroidApp.Context.PackageName;
                return AndroidApp.Context.PackageManager.GetLaunchIntentForPackage(packageName);
            }
        }

and Calling it

if (Device.RuntimePlatform == Device.Android)
   DependencyService.Get<ITheme>().OnThemeChanged();

Is there any way to update application theme irrespective of OS theme (Dark/Light) without restarting the MainActivity?


Solution

  • My bad, I guess I was wrong. The code in my question works as expected. I don't need to have that Android Service to restart activity. Calling below from any where changes the theme to Dark irrespective of OS theme.

    Application.Current.UserAppTheme = OSAppTheme.Dark;