切记在style中把
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">换成
<style name="AppTheme" parent="Theme.AppCompat.DayNight.DarkActionBar">
1创建values-night
2复制color、strings文件
color/夜间
<resources> <color name="colorPrimary">#54565e</color> <color name="colorPrimaryDark">#383a48</color> <color name="colorAccent">#2e2a2c</color> <color name="background">#2e2a2c</color> <color name="text_color">#f2ecef</color> </resources>color/日间
<resources> <color name="colorPrimary">#3F51B5</color> <color name="colorPrimaryDark">#303F9F</color> <color name="colorAccent">#FF4081</color> <color name="background">#fcfbfb</color> <color name="text_color">#0a0909</color> </resources>
strings/夜间
<resources> <string name="app_name">LianxiTab</string> <string name="change_to_content">夜间模式</string> </resources>string/日间
<string name="app_name">LianxiTab</string> <string name="change_to_content">日间模式</string>
3在Applicationg oncreate方法中添加
if (getSharedPreferences("theme", MODE_PRIVATE).getBoolean("night_theme", false)) { AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES); }4Mainactivity方法中
//日夜间模式转换 public void change(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(); }