其实本篇要讲的内容很简单,只讲切换Theme这种切换夜间模式的方法。
首先要确定你在切换时要改变的有哪几个属性,比如我在切换夜间模式时改变了背景颜色,title的字体颜色,还有正文的字体颜色。所以相应的定义这三种属性:
在values目录下新建attrs.xml 文档,其中定义你要的属性,命名随意符合规范就好。
<?xml version="1.0" encoding="utf-8"?> <resources> <attr name="title_color" format="color"/> <attr name="content_color" format="color"/> <attr name="bg_color" format="color"/> </resources>
<style name="dayTheme" parent="AlertDialog.AppCompat"> <item name="bg_color">#eeeeee</item> <item name="title_color">#111111</item> <item name="content_color">#333333</item> </style> <style name="nightTheme" parent="AlertDialog.AppCompat"> <item name="bg_color">#77111111</item> <item name="title_color">#eeeeee</item> <item name="content_color">#ccddcc</item> </style>
然后在你要在切换模式时改变显式的View的XML文件里在用到颜色的时候用你定义的在上面定义的属性,蓝色的两行表示在取颜色的时候指向你定义的资源属性,不同模式下,分别代表不同的值。
<TextView android:id="@+id/text_title" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:text="@string/text_title" android:textColor="?attr/title_color" android:textSize="20sp" /> <TextView android:id="@+id/text_content" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_below="@id/text_title" android:layout_marginTop="20dp" android:textColor="?attr/content_color" android:text="@string/text_contet" android:textSize="16sp" />
定义一个静态变量,来存储你当前设置的模式,也可以用SharedPreferences来存储,区别就是前者重启APP后还是默认值,后者把夜间模式的设置存在了本地。只要不清缓存,设置一直都有效,这里为了简单,就用静态变量保存了。setTheme一定要放在setContentView之前,不知道为什么就去看
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (isNight){ setTheme(R.style.nightTheme); }else { setTheme(R.style.dayTheme); } setContentView(R.layout.activity_main);
在切换模式操作时,只需要:
//change day and night theme isNight = !isNight; recreate();
总结一下,主要是四步:首先,确定在切换模式时要改变的属性,自己在attrs文件中定义。然后,定义两套在styles中定义两套theme,给自己定义的attr赋予不同的值。然后,在布局文件中用?attr/的方式引用。最后,在代码中要改模式时,在onCreate时先判断要用哪个主题。设置时只需要把标志设为要取的那个theme供下一次onCreate判断就好。多说一句,多种模式切换也是一样的,多几种判断而已,不管你要日间模式,夜间模式,小清新模式,或者猥琐模式,只是改改背景换换颜色而已,原理都一样。还有改变字体或者字体大小也是一样的,只不过对应的attr改为字体类型或者字体大小而已。
搞定,非常简单的东西,请勿嘲笑,慢慢由浅到深的学习。最后demo传送门: