c# - 切换日夜主题 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;
}
我认为这不是正确的方法。
解决方案
首先,您的代码刚刚在 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
方法中使用。这是运行截图。
更新
这是我的演示。 https://github.com/851265601/Xamarin.Android_ListviewSelect/blob/master/App16.zip
推荐阅读
- ssas - 引用另一个表的 SSAS 命名计算
- javascript - 获取一周中给定两天之间的天数
- arrays - 在 PowerShell 中查找和替换
- c# - 如何将具有不同列标题的 .csv 文本文件中的数据导入内存
- docker - 在 Visual Studio 中使用相同的 docker 文件构建 docker 映像的 Azure Pipeline 失败
- javascript - 为什么如果单击按钮两次 setInterval 方法比声明的更短
- firebase - Flutter 中的 Firebase 复杂查询
- mongodb - 从 mongodb 3.6 升级到 4.0 后如何在没有退出代码的情况下重新启动服务器
- sql-server - 如何保持某些列原样并动态旋转 SQL Server 2012 中的最后一列
- windows - 如何更改本地 Appdata 位置