Android夜间模式原理及实现方法

其实本篇要讲的内容很简单,只讲切换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>



然后在values下的styles文件中创建你要的两种模式,一种日间模式,一种夜间模式。在这两种模式中给你在上面attrs中定义的资源属性名赋予不同的值。

<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之前,不知道为什么就去看

activity界面架构即activity视图层结构 

 

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传送门:

https://github.com/angularzues/NightThemeTest.git

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值