一、要求:
在应用内实现可以切换多套主题(指使用不同的背景颜色、字体颜色、图片等)
二、方法步骤:
(一)定义需要实现切换的资源对应的属性
在res文件夹下的values下新建attrs.xml文件
<?xml version=1.0 encoding="utf-8"?>
<resources>
<attr name="infobar_background" format="reference/color"/>
<attr name="infobar_text_color" format="color"/>
<attr name="infobar_dolby" format="reference"/>
</resources>
附:Android中自定义属性的格式详解(仅展示常用两种,其他自行百度)
1. reference:指引用某一资源ID。
(1)属性定义:
<declare-styleable name = "名称">
<attr name = "background" format = "reference" />
</declare-styleable>
(2)属性使用:
<ImageView
android:layout_width = "42dip"
android:layout_height = "42dip"
android:background = "@drawable/图片ID"/>
2. color:颜色值。
(1)属性定义:
<declare-styleable name = "名称">
<attr name = "textColor" format = "color" />
</declare-styleable>
(2)属性使用:
<TextView
android:layout_width = "42dip"
android:layout_height = "42dip"
android:textColor = "#00FF00"
/>
注:属性定义时可以指定多种类型值。
(1)属性定义:
<declare-styleable name = "名称">
<attr name = "background" format = "reference|color" />
</declare-styleable>
(2)属性使用:
<ImageView
android:layout_width = "42dip"
android:layout_height = "42dip"
android:background = "@drawable/图片ID|#00FF00" />
(二)新建需要的不同主题,并对上面的相关属性进行赋值
在values/style.xml(也可以重新新建一个专门用于主题切换的xml)中新建你想要的主题,主题名称自定义即可,然后对相应的属性进行赋值。
此处新建了三个主题,分别应用这三个主题时系统会自动调用对应的资源。
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="fte_v6">
<item name="infobar_background">@drawable/图片名_v6|#f1f1f1</item>
<item name="infobar_text_color">#ee9c18</item>
<item name="infobar_dolby">@drawable/图片名_v6</item>
</style>
<style name="fte_v5">
<item name="infobar_background">@drawable/图片名_v5|#f1f1f1</item>
<item name="infobar_text_color">#ee9c18</item>
<item name="infobar_dolby">@drawable/图片名_v5</item>
</style>
<style name="fte_v6_mura">
<item name="infobar_background">@drawable/图片名_mura|#f1f1f1</item>
<item name="infobar_text_color">#eeeeee</item>
<item name="infobar_dolby">@drawable/图片名_mura</item>
</style>
</resources>
(三)在控件中引用相应的属性
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="?attr/infobar_background"
android:orientation="vertical" >
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textColor="?attr/infobar_text_color"/>
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textColor="?infobar_text_color"/>此处省略attr是可以的
</LinearLayout>
(四)设置相应的主题
在activity的oncreate中调用setTheme(R.style.fte_v6),参数即为自己定义的主题名称(注意setTheme方法必须在setContentView之前调用)。
关于主题切换目前使用的是通过属性来判断使用哪种主题,根据不同的属性值设置不同的主题。