[英]Support both light and dark theme in Android Pie
Android Pie added the ability to toggle light/dark theme in the Settings -> Display -> Device Theme menu. Android Pie在“设置”->“显示”->“设备主题”菜单中添加了切换亮/暗主题的功能。
I want my app to apply the correct theme according to the Device Theme set in the device settings. 我希望我的应用根据设备设置中设置的“设备主题”应用正确的主题。
According to the Styles and Themes Android guide, for dark mode the app should use a theme that extends Theme.AppCompat
, and for light mode the app should use a theme that extends Theme.AppCompat.Light
. 根据Android 样式和主题指南,对于黑暗模式,应用程序应使用扩展
Theme.AppCompat
的主题,对于明亮模式,应用程序应使用扩展Theme.AppCompat.Light
的主题。
So I created two themes in my app: 因此,我在应用程序中创建了两个主题:
<style name="AppTheme.Dark" parent="Theme.AppCompat">
...
</style>
<style name="AppTheme.Light" parent="Theme.AppCompat.Light">
...
</style>
However in AndroidManifest.xml
when I declare the application with the <application>
tag I can only specify one theme in the android:theme
attribute: 但是在
AndroidManifest.xml
当我使用<application>
标签声明应用程序时,我只能在android:theme
属性中指定一个主题:
<application
android:name=".MyApplication"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher"
android:supportsRtl="true"
android:theme="@style/AppTheme.Light"
tools:replace="android:name">
How do I declare my application in AndroidManifest.xml
to dynamically pick @style/AppTheme.Light
or @style/AppTheme.Dark
according to the Device Theme set in the device settings? 如何在
AndroidManifest.xml
声明我的应用程序,以根据设备设置中设置的设备主题动态选择@style/AppTheme.Light
或@style/AppTheme.Dark
?
If you want to change theme of an already existing activity, call recreate() after setTheme(). 如果要更改现有活动的主题,请在setTheme()之后调用recreate()。
Note: don't call recreate if you change theme in onCreate(), to avoid infinite loop. 注意:如果您在onCreate()中更改主题,请勿调用recreate,以避免无限循环。
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Call setTheme before creation of any(!) View.
setTheme(android.R.style.Theme_Dark);
// ...
setContentView(R.layout.main);
}
You may want to try Theme.AppCompat.DayNight
instead of defining two themes. 您可能想要尝试
Theme.AppCompat.DayNight
而不是定义两个主题。 Its implementation in this video Cost of a Pixel Color . 在此视频中实现像素成本的成本 。
However, when I test this on an emulator, toggling Settings -> Display -> Device Theme menu doesn't work. 但是,当我在模拟器上进行测试时,切换设置->显示->设备主题菜单不起作用。 I have to toggle Developer Options -> Night Mode -> Always On and dark theme is picked automatically.
我必须切换“开发人员选项”->“夜间模式”->“始终打开”,然后自动选择黑暗主题。
Since I don't own an Android Pie device, I'm not sure if this is a bug of emulator. 由于我没有Android Pie设备,因此不确定这是否是模拟器的错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.