根据文档,我只需要在我的活动清单中设置
我试图通过以下代码获取活动主题名称:
android:forceDarkAllowed=true
并继承主题parent="Theme.MaterialComponents.DayNight"
。 我试过了,但它没有起作用。
这是我的清单文件:
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:name=".MainActivity"
android:forceDarkAllowed="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
这是我的styles.xml
样式:
<style name="AppTheme" parent="Theme.MaterialComponents.Light">
...
</style>
<style name="AppTheme.Dark" parent="Theme.MaterialComponents.DayNight">
...
</style>
我试图通过以下代码获取活动主题名称:
:
resources.getResourceName(
packageManager.getPackageInfo(packageName, PackageManager.GET_META_DATA)
.applicationInfo.theme
)
它显示给我com.example.name:style/AppTheme
而不是AppTheme.Dark
。我该如何让MainActivity
在运行应用程序时自动将自身设置为使用AppTheme.Dark
(即暗模式),使用android:forceDarkAllowed
?
android:forceDarkAllowed
部分感到非常困惑。我会再次尝试重新阅读它,看看是否有遗漏的内容。真的非常感谢你,这太完美了。 - Richardandroid:forceDarkAllowed
主要是为了现有的应用程序,想要尝试在不重新设计其主题和用户界面的情况下添加深色模式支持。它的效果出奇的好,但仍然会犯错误。您需要彻底测试您的应用程序,以确认自动转换不会使一些内容变得丑陋或无法使用。 - CommonsWareTheme.AppCompat
和Theme.MaterialComponents
上测试了android:forceDarkAllowed
,它确实像你所说的那样工作。它神奇地将颜色转换为暗色主题模式。然后,我在Theme.AppCompat.DayNight/Light
和Theme.MaterialComponents.Light/DayNight
上再次尝试,但却没有起作用。 - Richard首先,Android 不会在任何时候自动将 .Dark 添加到你的主题中
,立刻得出结论,这个答案来自于 CommonsWare。 - Bugs Happen