【Android】非 recreate() 形式的夜间模式实现(自由切换,不改变任何状态,不重新初始化整个activity)

之前接到“夜间模式”的需求,因为页面多,所以就打算先简单做。

找的资料基本上都是 recreate() 的形式:先在 SharedPreferences 里面记录一个标识,然后通过 recreate() 重新初始化 activity,在 onCreate() 方法里根据标识通过 setTheme() 去修改主题 Theme(该方法在 setContentView() 之前调用)。

在 attrs.xml 里面声明一套属性(可以是 color,也可以是 reference,前者是颜色,后者是 drawable),其中 styles.xml 中定义了 日间、夜间 两个主题(如果主题文件区分系统版本,那么每个版本下的 styles.xml 都得设置),两个主题都分别对 attrs.xml 里声明的属性进行定义,然后布局 XML 中就通过 ?attr/xxxx 去设置颜色或 drawable,这样切换主题后就能直接切换对应模式下的颜色或 drawable。

下面简单的放下代码:

attrs.xml:

<resources>

 <attr name="color_text" format="color" />

 <attr name="drawable_icon" format="reference" />
</resources>

styles.xml:

<style name="AppTheme" parent="Theme.AppCompat.Light">
 
    <!-- toolbar(actionbar)颜色 -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <!-- 状态栏颜色 -->
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <!-- 窗口的背景颜色 -->
    <item name="android:windowBackground">@color/colorPrimary</item>
   
    <item name="color_text">@color/sun_text_color</item>
    
    <item name="drawable_icon">@drawable/ic_chevron_right_white_24dp</item>
</style>

<style name="AppThemeDark" parent="Theme.AppCompat">
 
    <!-- toolbar(actionbar)颜色 -->
    <item name="colorPrimary">@color/darkcolorPrimary</item>
    <!-- 状态栏颜色 -->
    <item name="colorPrimaryDark">@color/darkcolorPrimaryDark</item>
    <!-- 窗口的背景颜色 -->
    <item name="android:windowBackground">@color/darkcolorPrimary</item>
        
    <item name="color_text">@color/night_text_color</item>
    <item name="drawable_icon">@drawable/ic_chevron_right_black_24dp</item>
</style>

然后布局 xml 文件里面直接用:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <ImageView
        android:id="@+id/iv_about"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:scaleType="centerCrop"
        android:src="?attr/drawable_icon" />

    <TextView
        android:id="@+id/tv_bottom"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Copyright"
        android:textColor="?attr/color_text"
        android:textSize="12sp" />

</LinearLayout>

到这里应该很多人会问为什么还要说这个,这个方案不是跟标题不符合么?其实这个方案后面还是需要用到的,所以就先贴出来。

<
  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值