AppCompat DayNight主题在Android 6.0上不起作用? [英] AppCompat DayNight theme not work on Android 6.0?

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

问题描述

我正在使用Android Support Library 23.2

在Android 5.1上,它运行良好.

On Android 5.1 it works well.

在Android 6.0上,活动看起来像是使用浅色主题,而对话框看起来是使用深色主题.

On Android 6.0, activity looks like using light theme, but dialog looks using dark theme.

我的应用程序类:

public class MyApplication extends Application {
    static {
        AppCompatDelegate.setDefaultNightMode(
                AppCompatDelegate.MODE_NIGHT_YES);
    }
}

我的styles.xml

My styles.xml

<style name="AppTheme" parent="Theme.AppCompat.DayNight">
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>

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

显示对话框的代码:

new AlertDialog.Builder(mContext, R.style.Dialog_Alert)
                .setTitle("Title")
                .setMessage("Message")
                .show();

推荐答案

最好的解决方案是使用适当的配置更新上下文.这是我的工作摘要:

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

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

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