public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button button = (Button) findViewById(R.id.btn_main); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //必须定义为 uimode 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); shared(false); break; case Configuration.UI_MODE_NIGHT_NO: AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES); shared(true); break; } //重启activity recreate(); } }); } //存入状态 private void shared(boolean flag){ SharedPreferences sp = getSharedPreferences("Info", MODE_PRIVATE); SharedPreferences.Editor edit = sp.edit(); edit.putBoolean("Day",flag); edit.commit(); } } //定义Myapp记得注册public class Myapp extends Application { @Override public void onCreate() { super.onCreate(); //获取状态 SharedPreferences info = getSharedPreferences("Info", MODE_PRIVATE); boolean day = info.getBoolean("Day", false); if (day){ AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES); }else { } } }
//style<resources> <!-- Base application theme. --> //切换为 Theme.AppCompat.DayNight.DarkActionBar <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>
切换夜间模式
最新推荐文章于 2019-09-24 11:16:17 发布