先在values下的colors.xml定义一组夜间模式的颜色:
<color name="night_colorPrimary">#464646</color> <color name="night_colorPrimaryDark">#464646</color> <color name="night_colorAccent">#0A2B43</color>
在values下创建brackgrendcolor.xml 文件:
<?xml version="1.0" encoding="utf-8"?> <resources> <attr name="brackgrendcolor" format="color"></attr> <attr name="textconten" format="string"></attr> </resources>
在styes.xml中写入一组夜间模式样式:
<!-- Base application theme. --> <style name="Night_AppTheme" parent="Theme.AppCompat.Light.NoActionBar"> <!-- Customize your theme here. --> <item name="colorPrimary">@color/night_colorPrimary</item> <item name="colorPrimaryDark">@color/night_colorPrimaryDark</item> <item name="colorAccent">@color/night_colorAccent</item>//要跟你自己 创建的文件名一样 <item name="brackgrendcolor">@android:color/black</item> <item name="android:textColor">@android:color/white</item> </style>
然后在avtivity_main.xml里:
在主背景中写:
//名字同样是你自己创建的文件名
android:background="?attr/brackgrendcolor"
写一个监听按钮用来切换模式。
在MainActivity里:
//定义一个默认模式
private int theme=R.style.AppTheme;
//在onCreata下:
if (savedInstanceState!=null){ theme=savedInstanceState.getInt("theme"); setTheme(theme); }
//在你写的监听方法里写:
public void btuu1(View view){ theme=(theme==R.style.AppTheme)?R.style.Night_AppTheme :R.style.AppTheme; MainActivity.this.recreate(); }在写两个方法:@Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putInt("theme",theme); } @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); theme=savedInstanceState.getInt("theme"); }到这里背景的切换就完成了。文字的切换:在自己定义的values下的文件里:加入<attr name="textconten" format="string"></attr>在string.xml里加入:<string name="naght_text">夜间模式</string> <string name="day_text">日间模式</string>在styles.xml里的日间样式和夜间样式里分别加入://加在日间样式里<item name="textconten">@string/naght_text</item>//加在夜间样式里<item name="textconten">@string/day_text</item>在activity_main.xml里写入://和上述的监听方法是一样的<TextView android:onClick="btuu1" android:layout_width="match_parent" android:layout_height="wrap_content"//切换文字 android:text="?attr/textconten" />完成。图片的切换:现在drawable文件加里添加两张图片;分别在styles.xml里的日间样式和夜间样式添加://日间样式<item name="android:drawable">@drawable/dra1</item>//夜间样式<item name="android:drawable">@drawable/gd2</item>在activity_main.xml里写入:<ImageView android:id="@+id/image2" android:layout_width="wrap_content" android:layout_height="wrap_content"//切换图片 android:background="?android:drawable" />//完成