根据文档,我只需要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
(即暗模式) using android:forceDarkAllowed
?