之前接到“夜间模式”的需求,因为页面多,所以就打算先简单做。
找的资料基本上都是 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>
到这里应该很多人会问为什么还要说这个,这个方案不是跟标题不符合么?其实这个方案后面还是需要用到的,所以就先贴出来。