AppCompat MODE_NIGHT_AUTO不起作用 [英] AppCompat MODE_NIGHT_AUTO not working

查看:125
本文介绍了AppCompat MODE_NIGHT_AUTO不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

AppCompatDelegate.MODE_NIGHT_AUTO没有更新我现有的活动,我不确定为什么.

AppCompatDelegate.MODE_NIGHT_AUTO is not updating my existing activity and I'm not sure why.

我动态地允许用户更改夜间模式.如果用户将模式更改为自动,那么我将设置默认的夜间模式,然后重新创建活动:

I dynamically allow the user to change night mode. If the user changes the mode to auto I set the default night mode then recreate the activity:

AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_AUTO);
recreate();

如果我更改为MODE_NIGHT_YES或MODE_NIGHT_NO,它将按预期工作.如果我更改为MODE_NIGHT_AUTO,它将转到正确的暗/亮主题,但是从白天过渡到夜晚后,它将无法更新活动.测试此操作有点糟,因为我必须等待日出/日落(显然,我可以手动更改设备上的时间,而不必等待...只要不使用位置权限即可).

If I change to MODE_NIGHT_YES or MODE_NIGHT_NO, it works as expected. If I change to MODE_NIGHT_AUTO, it goes to the correct dark/light theme, but then it fails to update the activity after the transition from day to night. It kind of sucks to test this because I have to wait for sunrise/sunset ( apparently I can manually change the time on the device rather than having to wait...so long as the location permission is not used).

我是否必须手动检查onresume中的夜间模式标志并手动更新现有活动的资源,还是我做错了什么?如果我旋转设备并在日落之后重新创建活动,则可以正确拾取深色主题,但是在旋转之前,它将仍然显示浅色主题.

Do I have to do a manual check for the night mode flag in onresume and manually update resources for existing activities, or am I doing something wrong? If I rotate the device and the activity is recreated after sunset then the dark theme is correctly picked up, but before rotation it will still be showing the light theme.

支持lib 23.4.0,Android 6.0版.

Support lib 23.4.0, Android version 6.0.

推荐答案

万一其他人想知道我为解决这个问题做了什么(虽然不确定这样做是否正确):

In case anyone else wants to know what I did to solve this (not sure if it is the right way to do it though):

private int mCurrentNightMode;

@Override
protected void onCreate(Bundle savedInstanceState) {
   mCurrentNightMode = getCurrentNightMode();
}

@Override
protected void onPostResume() {
    super.onPostResume();

    if (hasNightModeChanged()) {
        delayedRecreate();
    }

}

private void delayedRecreate() {
    Handler handler = new Handler();
    handler.postDelayed(this::recreate, 1);
}

private boolean hasNightModeChanged() {
    getDelegate().applyDayNight();
    return mCurrentNightMode != getCurrentNightMode();
}

private int getCurrentNightMode() {
    return getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
}

这篇关于AppCompat MODE_NIGHT_AUTO不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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