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