首先日夜间模式分为三种。
以下展示的为第一种比较简单的方式。
1.在我们的styles下重新添加一套夜间模式的颜色
<resources xmlns:tools="http://schemas.android.com/tools"> //这里是系统默认提供的白天模式 <!-- Base application theme. --> <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar"> <!-- Customize your theme here. --> <item name="colorPrimary">@color/colorPrimary</item> <item name="colorPrimaryDark">@color/colorPrimaryDark</item> <item name="colorAccent">@color/colorAccent</item> <item name="android:textColor">@android:color/black</item> <item name="mainBackground">@android:color/white</item> </style> 下面就是需要我们自己添加进去的夜间模式 <style name="NightAppTheme" parent="Theme.AppCompat.Light.DarkActionBar"> <!-- Customize your theme here. --> <item name="colorPrimary">@color/nightColorPrimary</item> <item name="colorPrimaryDark">@color/nightColorPrimaryDark</item> <item name="colorAccent">@color/nightColorAccent</item> <item name="android:textColor">@android:color/white</item> <item name="mainBackground">@color/nightColorPrimaryDark</item> </style> 2.在代码中通过点击事件的监听的方法中书写下面的代码theme=(theme==R.style.AppTheme)?R.style.NightAppTheme:R.style.AppTheme; recreate();//这个方法主要用来重新启动Activity的生命周期 3.在最顶部创建一个int类型的字段来接受现在处于那种模式。 比如:private int mot=R.style.Apptheme; 4.在activity中的需要书写以下两种临时保存数据的方法 一个是存值,其中的父类给的方法需要删除掉@Override public void onSaveInstanceState(Bundle outState) { // super.onSaveInstanceState(outState); outState.putInt("theme",theme); }二一种就是取值得方法@Override protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); theme=savedInstanceState.getInt("theme"); } 5.在activity中的oncreate方法中书写以下代码 切记写在ContentView()这个代码之前if(savedInstanceState!=null){ theme=savedInstanceState.getInt("theme"); setTheme(theme); } 在代码中我们也可以根据theme的不同风格来判断我们索要进行的操作!