AppCompat DayNight theme not work on Android 6.0?

后端 未结 6 1329
眼角桃花
眼角桃花 2020-12-09 18:09

I am using the new Theme.AppCompat.DayNight added in Android Support Library 23.2

On Android 5.1 it works well.

On Android 6.0, act

6条回答
  •  悲哀的现实
    2020-12-09 18:52

    The best solution is to update context with proper config. Here is a snippet of what I do:

    public Context setupTheme(Context context) {
    
        Resources res = context.getResources();
        int mode = res.getConfiguration().uiMode;
        switch (getTheme(context)) {
            case DARK:
                AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
                mode = Configuration.UI_MODE_NIGHT_YES;
                break;
            case LIGHT:
                AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
                mode = Configuration.UI_MODE_NIGHT_NO;
                break;
            default:
                AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_AUTO);
                break;
        }
    
        Configuration config = new Configuration(res.getConfiguration());
        config.uiMode = mode;
        if (Build.VERSION.SDK_INT >= 17) {
            context = context.createConfigurationContext(config);
        } else {
            res.updateConfiguration(config, res.getDisplayMetrics());
        }
        return context;
    }
    

    Then use the context in your Application like so

    @Override
    protected void attachBaseContext(Context base) {
        Context context = ThemePicker.getInstance().setupTheme(base);
        super.attachBaseContext(context);
    }
    

提交回复
热议问题