根据docs ,我只需要设置android:forceDarkAllowed=true
在我的 Activity list 中并从 parent="Theme.MaterialComponents.DayNight"
继承主题.我试过了,但是没有用。
这是我的 list 文件:
<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>
我尝试使用以下代码获取 Activity 的主题名称:resources.getResourceName(
packageManager.getPackageInfo(packageName, PackageManager.GET_META_DATA)
.applicationInfo.theme
)
它告诉我com.example.name:style/AppTheme
而不是 AppTheme.Dark
.我怎样才能使它在我运行应用程序时,MainActivity
自动设置为使用 AppTheme.Dark
(即暗模式)使用 android:forceDarkAllowed
?
最佳答案
那不是dark mode适用于 Android 10。
首先,Android 不会神奇地追加 .Dark
无论用户是否启用暗模式,都可以随时添加到您的主题。你有 android:theme="@style/AppTheme"
.因此,Android 将使用 AppTheme
一直和你的AppTheme.Dark
不会被使用。
二、背后的理念DayNight
是您一直使用它作为基础主题,Android 将根据用户请求在正常模式和暗模式之间切换。所以,如果你切换 AppTheme
延长 DayNight
, 并摆脱 AppTheme.Dark
,您将匹配 the documentation呼吁。android:forceDarkAllowed
适用于您无法使用 DayNight
的情况主题,并且您希望 Android 尝试自动将您的 UI 转换为深色主题。如果您想保留 AppTheme
延长 Light
而不是 DayNight
,这可能会起作用(我个人没有尝试过使用 MaterialComponents
主题)。但是,即便如此,它也只会在用户启用暗模式时(例如,点击通知阴影图 block )。
例如,在 this sample app , 我用 DayNight
对于我的主题:
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.DayNight">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
</resources>
我在
res/values/
中对这些颜色有不同的定义和 res/values-night/
.我不使用 forceDarkAllowed
.而且,当用户切换夜间模式时,我的 UI 来自:至:
How can I make it so that when I run the application, the MainActivity automatically sets itself to use AppTheme.Dark (i.e. dark mode) using android:forceDarkAllowed?
你没有。
如果您一直想要一个深色主题,请使用常规主题(不是
Light
,而不是 DayNight
)。
关于android - 如何在 Android 上强制应用深色主题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60026842/