首页 > 解决方案 > 切换日夜主题 Android Xamarin

问题描述

我正在尝试使用 android daynight 主题在我的 android 应用程序中实现一个深色主题。它目前改变了主题,但我认为它不会像我想要的那样重新创建活动。在java中,他们 AppCompatDelegate.setDefaultNightMode()显然现在自动重新创建活动,但我找不到在xamarin android中执行此操作的c#方法?

我目前的实现是:

switch (selectedSpinnerItem)
{
    case "Light":
        ((AppCompatActivity)Activity).Delegate.SetLocalNightMode(AppCompatDelegate.ModeNightNo);
        break;
    case "Dark":
        ((AppCompatActivity)Activity).Delegate.SetLocalNightMode(AppCompatDelegate.ModeNightYes);
        break;
    case "System Preference":
        ((AppCompatActivity)Activity).Delegate.SetLocalNightMode(AppCompatDelegate.ModeNightFollowSystem);
         break;
 }

我认为这不是正确的方法。

标签: c#androidandroid-fragmentsxamarin.android

解决方案


首先,您的代码刚刚在 Android Q 中运行。 https://developer.android.com/guide/topics/ui/look-and-feel/darktheme#force_dark

如果你想让它工作,你也可以添加<item name="android:forceDarkAllowed">true</item>styles.xml喜欢的以下代码。

<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
        <item name="android:forceDarkAllowed">true</item>
    </style>

</resources>

我将它设置为((AppCompatActivity)this).Delegate.SetLocalNightMode(AppCompatDelegate.ModeNightYes);OnCreate方法中使用。这是运行截图。

在此处输入图像描述

更新

当我更改主题时,将创建 Activity。 在此处输入图像描述

这是我的演示。 https://github.com/851265601/Xamarin.Android_ListviewSelect/blob/master/App16.zip


推荐阅读