string.xml
<resources>
<string name="app_name">DayNightTwo</string>
<string name="change_to_content">切换成夜间模式</string>
</resources>
styles.xml
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.DayNight.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
</resources>
Application
public class App extends Application {
@Override
public void onCreate() {
super.onCreate();
if (getSharedPreferences("theme", MODE_PRIVATE).getBoolean("night_theme", false)) {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
}
}
}
Maintivity
public void onClick(View v) {
//切换日夜间模式
int uiMode;
uiMode = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
switch (uiMode) {
case Configuration.UI_MODE_NIGHT_YES:
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
getSharedPreferences("theme", MODE_PRIVATE).edit().putBoolean("night_theme", false).commit();
break;
case Configuration.UI_MODE_NIGHT_NO:
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
getSharedPreferences("theme", MODE_PRIVATE).edit().putBoolean("night_theme", true).commit();
break;
}
recreate();
}