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
?
OSAppTheme currentTheme = Application.Current.RequestedTheme;
? docs.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/… – Mihail Duchevto update application to follow the OS theme
. What you want is not to change "OS" theme, but to have an independent app theme, which doesn't track the configuration of OS theme. – Mihail Duchev