根据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
(即暗模式)?
答案 0 :(得分:2)
gradle
中的目标SDK为29。答案 1 :(得分:1)
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
主题)。但是,即使那样,也只有在用户启用了暗模式时(例如,在通知阴影图块上点按),即可。
例如,在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来自:
收件人:
如何做到这一点,以便在运行应用程序时,MainActivity会通过android:forceDarkAllowed自动设置为使用AppTheme.Dark(即黑暗模式)?
你没有。
如果您一直想要深色主题,请使用常规主题(不是Light
,而不是DayNight
)。