Android:如何将主题切换为黑暗模式? [英] Android: How to switch theme for dark mode?

查看:1040
本文介绍了Android:如何将主题切换为黑暗模式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从Android 10开始,您可以在暗模式和默认亮模式之间切换.由于这是一个新主题,因此我尚未对此进行更深入的研究. OS是否自动进行了暗模式的颜色切换,或者如果暗模式已打开,是否有任何方法告诉我的应用切换不同的应用主题?另外,某些Android 9设备也可以使用暗模式.

Since Android 10, you can switch between dark mode and default light mode. I didn't make any closer research yet on this since it's a new topic. Is Dark mode color switching automatic by OS or is there any way to tell my App to switch different app-theme if Dark mode is turned on? Also dark mode is possibility for some Android 9 devices.

因为我使用自定义参数制作了自定义深色主题,并且为资源中的每种颜色设置了深色(在attrs.xml中使用自定义属性,并在styles.xml中的主题中将特定的颜色资源应用于它们).同样,它适用于我的应用程序的不同配色方案(例如,蓝色,红色,绿色).这样一来,我就能分辨出哪种颜色将用于我的应用程序而不是系统中的不同视图.

Because I made custom Dark theme with custom parameters and I set dark color for each of my color in resources (using custom attributes in attrs.xml and applied specific color resource to them inside theme in styles.xml). Same it is working for different color schemes of my App (blue, red, green for example). That way I can tell which color would be used for different views in my App and not system.

我唯一需要做的就是检测系统中是否启用了暗模式.我可以强制用户在应用"设置(自定义设置)中打开暗"模式,但主题可能会受到系统暗"模式(在电话"设置中打开)的影响.

Only thing I need is to detect if dark mode is on/off in system. I can force user to turn on Dark mode in App settings (custom settings) but theme can be affected by system dark mode (turned on in Phone settings).

推荐答案

来自官方文档:

为了支持深色主题,您必须将应用程序的主题(通常在res/values/styles.xml中找到)设置为从DayNight主题继承:

In order to support Dark theme, you must set your app's theme (usually found in res/values/styles.xml) to inherit from a DayNight theme:

<style name="AppTheme" parent="Theme.AppCompat.DayNight">

您还可以使用MaterialComponents的深色主题:

You can also use MaterialComponents' dark theming:

<style name="AppTheme" parent="Theme.MaterialComponents.DayNight">

这会将应用程序的主主题与系统控制的夜间模式标志相关联,并为应用程序提供默认的深色主题(启用时).

This ties the app's main theme to the system-controlled night mode flags and gives the app a default Dark theme (when it is enabled).

这意味着,如果您使用DayNight主题,则操作系统本身会处理该应用程序主题.如果您想强制应用使用深色主题,请检查这个文档.

It means that if you use a DayNight theme, the OS itself handles the app theme. if you want to force app uses dark theme check this documentation.

要检测设备主题:

switch (getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK) {
    case Configuration.UI_MODE_NIGHT_YES:
        …
        break;
    case Configuration.UI_MODE_NIGHT_NO:
        …
        break; 
}

这篇关于Android:如何将主题切换为黑暗模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆