How to automatically switch to dark mode on Android app?

橙三吉。 提交于 2020-02-25 06:20:47

问题


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.


回答1:


Maybe you can have a look at AppCompatDelegate.setDefaultNightMode()

you simply define your theme with the parent of DayNight:

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

and each style with:

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

or

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

and then you can call : AppCompatDelegate.setDefaultNightMode()

with one of these:

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);
    }
}

more info here



来源:https://stackoverflow.com/questions/59134005/how-to-automatically-switch-to-dark-mode-on-android-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!