如何以编程方式启用夜间模式? [英] How to enable night mode programmatically?

查看:158
本文介绍了如何以编程方式启用夜间模式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种使用Android代码以编程方式启用夜间模式的方法:

I am looking for a way to enable night mode programmatically with an Android code:

public static void setNightMode(Context target , boolean state){

    UiModeManager uiManager = (UiModeManager) target.getSystemService(Context.UI_MODE_SERVICE);

    if (state) {
        //uiManager.enableCarMode(0);
        uiManager.setNightMode(UiModeManager.MODE_NIGHT_YES);
    } else {
       // uiManager.disableCarMode(0);
        uiManager.setNightMode(UiModeManager.MODE_NIGHT_NO);
    }
}

我的屏幕上没有任何变化,夜间模式仍处于禁用状态. 根据此链接

Nothing has changed on my screen, the night mode is still disables. According to this link

无需启用carMode或deskMode. 我在Android Studio上有以下日志记录:

There is no need to enable carMode or deskMode. I have the following logcat on Android Studio:

11-26 12:15:16.662 3823-3823/? D/UiModeManager: updateConfigurationLocked: mDockState=0; mCarMode=false; mNightMode=2; uiMode=33
11-26 12:15:26.802 3823-3823/? V/UiModeManager: updateLocked: null action, mDockState=0, category=null

推荐答案

确保在 styles.xml 文件中将默认主题从Theme.AppCompat.Light.DarkActionBar更改为Theme.AppCompat.DayNight.DarkActionBar,然后执行切换到夜间模式.我已经在APIv23(Android 6.0)及更高版本中对其进行了测试,并且工作正常. 有关更好的说明,请参见

Make sure to change the default theme from Theme.AppCompat.Light.DarkActionBar to Theme.AppCompat.DayNight.DarkActionBar in the styles.xml file and then do AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES) to switch to the night mode. I have tested it in APIv23(Android 6.0) and above and it is working fine. For a better explanation see this codelab by Android

这篇关于如何以编程方式启用夜间模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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