原始問題:
加載應用程式時,我的應用程式狀態欄似乎對 android 系統主題更改沒有反應。
狀態欄僅在重新啟動后更新。請看下面的視頻:
此視頻顯示加載時正確應用于應用狀態欄的輕主題。但是在加載應用程式后,如果用戶將系統主題更改為深色,則應用程式的狀態欄不會更新,直到應用程式重新啟動。
從淺到深的主題示例視頻。
此視頻顯示加載時正確應用到應用狀態欄的深色主題。但是在加載應用程式后,如果用戶將系統主題更改為淺色,則應用程式的狀態欄不會更新,直到應用程式重新啟動。
深色到淺色主題示例視頻。
任何人都知道如何在加載應用程式時讓狀態欄對系統主題更改做出反應?
更新 1:
以下內容在控制臺中回傳所選主題的值,但是一旦我取消注釋Application.Current.UserAppTheme = AppTheme.Dark;,當我更改系統主題時,控制臺中不會回傳任何值。
private void ChangeTheme()
{
Application.Current.RequestedThemeChanged = (s, a) =>
{
AppTheme currentTheme = Application.Current.RequestedTheme;
if (currentTheme is AppTheme.Dark)
{
Console.WriteLine(currentTheme.ToString());
//Application.Current.UserAppTheme = AppTheme.Dark;
}
else if (currentTheme is AppTheme.Light)
{
Console.WriteLine(currentTheme.ToString());
}
};
}
更新 2:
我在 Platforms > Android > Resources > values 和 values-night 中使用 2 個不同的 styles.xml 檔案來設定狀態欄顏色。
uj5u.com熱心網友回復:
在您的MainActivity.cs中,您可以覆寫該OnConfigurationChanged()方法并監聽 UI 配置更改:
public override void OnConfigurationChanged(Configuration newConfig)
{
base.OnConfigurationChanged(newConfig);
if (Build.VERSION.SdkInt < BuildVersionCodes.R)
{
return;
}
if (newConfig.IsNightModeActive)
{
Window?.SetStatusBarColor(Colors.Black.ToAndroid());
Window?.InsetsController?.SetSystemBarsAppearance(0, (int)WindowInsetsControllerAppearance.LightStatusBars);
}
else
{
Window?.SetStatusBarColor(Colors.White.ToAndroid());
Window?.InsetsController?.SetSystemBarsAppearance((int)WindowInsetsControllerAppearance.LightStatusBars, (int)WindowInsetsControllerAppearance.LightStatusBars);
}
}
您還需要ConfigChanges.UiMode在屬性中包含標志ConfigurationChanges(默認包含在新的 MAUI 專案中):
[Activity(Theme = "@style/MyAppTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation | ConfigChanges.UiMode | ConfigChanges.ScreenLayout | ConfigChanges.SmallestScreenSize | ConfigChanges.Density)]
public class MainActivity : MauiAppCompatActivity
更新
關于您的情況下的RequestedThemeChanged事件和RequestedTheme屬性:當您進行設定時Application.Current.UserAppTheme = AppTheme.Dark;,您實際上是在說您希望將主題永久設定為Dark,因此在此之后不再引發事件,因為UserAppTheme不再設定為Unspecified。查看更多:https ://learn.microsoft.com/en-us/dotnet/maui/user-interface/system-theme-changes#set-the-current-user-theme
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/526011.html
