如何在Android应用程序上自动切换到黑暗模式? [英] How to automatically switch to dark mode on Android app?

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

问题描述

我正在制作一个Android应用.我为黑暗模式制作了另一个UI.所以这就是我所需要的;该应用程序将在当地时间自动切换为深色主题.例如,当当地时间太阳下山时,应用程序将切换到黑暗模式.

I'm making an Android app. I made another UI for dark mode. So this is what I need; the app will switch to dark theme automatically by the local time. For example, when the sun goes down by the local time, app will be switched to dark mode.

或者另一种选择是在一天中的预设时间切换到黑暗模式.希望你理解我的问题.如果有人知道,请帮助我,如果可能的话,我宁愿选择第一种方法.预先感谢.

Or another alternative is switching to dark mode by pre-setted time of the day. Hope you understand my problem. Please help me if anyone knows, I prefer the first option to do if it's possible. Thanks in advance.

推荐答案

也许您可以看看 AppCompatDelegate.setDefaultNightMode()

您只需与DayNight的父级一起定义主题:

you simply define your theme with the parent of DayNight:

<style name="MyTheme" parent="Theme.AppCompat.DayNight">    
<!-- Blah blah -->
</style>

以及每种样式:

<style name="Theme.AppCompat.DayNight" 
       parent="Theme.AppCompat.Light" />

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

然后您可以致电:AppCompatDelegate.setDefaultNightMode()

其中之一:

MODE_NIGHT_NO. Always use the day (light) theme.
MODE_NIGHT_YES. Always use the night (dark) theme.
MODE_NIGHT_FOLLOW_SYSTEM (default). This setting follows the system’s setting, which on Android Q and above is a system setting (more on this below).
MODE_NIGHT_AUTO_BATTERY. Changes to dark when the device has its ‘Battery Saver’ feature enabled, light otherwise.
MODE_NIGHT_AUTO_TIME & MODE_NIGHT_AUTO. Changes between day/night based on the time of day.

您通常会在自己的自定义应用程序类中执行此操作:

you would typically do this in your own custom application class:

public class MyApplication extends Application {

    public void onCreate() {
        super.onCreate();        
        AppCompatDelegate.setDefaultNightMode(
            AppCompatDelegate.MODE_NIGHT_YES);
    }
}

更多信息此处

这篇关于如何在Android应用程序上自动切换到黑暗模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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