.Dark
神奇地附加到主题上,无论用户是否启用了暗模式。您有android:theme="@style/AppTheme"
。因此,Android将一直使用AppTheme
,而您的AppTheme.Dark
将不会被使用。根据docs,我只需要在活动清单中设置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
(即暗模式)?
gradle
中的目标SDK为29。有两种方法可以应用深色主题:.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
主题)。但是,即使那样,也只有在用户启用了暗模式(例如,在通知阴影图块上点按)时才可以。
例如,在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/
中的这些颜色有不同的定义。我不使用res/values-night/
。而且,当用户切换夜间模式时,我的用户界面来自:
至:
“ >>
我如何做到这一点,以便在我运行应用程序时,MainActivity可以通过android:forceDarkAllowed自动将自己设置为使用AppTheme.Dark(即黑暗模式?)>
您不。
.Dark
神奇地附加到主题上,无论用户是否启用了暗模式。您有android:theme="@style/AppTheme"
。因此,Android将一直使用AppTheme
,而您的AppTheme.Dark
将不会被使用。