风格为一个view或窗体的多个视觉上的属性集合。
比如以下的layoutXML:
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#00FF00"
android:typeface="monospace"
android:text="@string/hello" />
你可以把它改为:
<TextView
style="@style/CodeFont"
android:text="@string/hello" />
所有的风格相关属性都从layout XML 文件中分离出来并且加入到风格定义类型 CodeFont中
,使用 style
属性。
1.定义风格
首先在res/values/文件目录下创建你的.xml文件,该文件的根节点为<resources>。对于任意一个style类型,你必须添加一个<style>元素包含name 属性标识它的唯一性。然后添加风格的每个属性为<item>元素,同时name属性指明它的属性和对应的值。如下例:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="CodeFont" parent="@android:style/TextAppearance.Medium">
<item name="android:layout_width">fill_parent</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:textColor">#00FF00</item>
<item name="android:typeface">monospace</item>
</style>
</resources>
2.继承
<style>中的parent属性可以使你继承某个存在的风格然后你只需要定义你想要改变或添加的属性。如下例你可以继承一个Android平台默认text外观然后修改它:
<style name="GreenText" parent="@android:style/TextAppearance">
<item name="android:textColor">#00FF00</item>
</style>
如果你继承你已经定义的风格,只添加你已定义风格作为前缀,中间用点号分割,作为name属性值,如下例继承了CodeFont风格,但是改变了颜色为红色:
<style name="CodeFont.Red">
<item name="android:textColor">#FF0000</item>
</style>
需要注意的是上面这种定义的方式只适用于自己定义的风格类型,对于系统内置的风格,比如TextAppearance必须使用parent属性。
3.对Activity和程序使用主题
为程序或activities设置主题,打开AndroidManifest.xml,编辑 <application>
标签包含 android:theme
属性. 例如:
<application android:theme="@style/CustomTheme">
如果你只需要设置一个activity的主题, 只需要添加 android:theme
属性到 <activity>
标签.
Andorid提供了很多内置资源,有许多预定义的主题可以使用,例如,你可以使用Dialog主题使你的Activity看起来像Dialog:
<activity android:theme="@android:style/Theme.Dialog">
或者你想让背景变成透明的,使用 Translucent主题:
<activity android:theme="@android:style/Theme.Translucent">
如果你想使用系统地主题,但是又要修改部分,可以添加主题作为你的主题的parent。例如,你可以修改传统dialog主题来使用你自己的背景图片如下:
<style name="CustomDialogTheme" parent="@android:style/Theme.Dialog">
<item name="android:windowBackground">@drawable/custom_dialog_background</item>
</style>
在Android Manifest中使用 CustomDialogTheme
取代 Theme.Dialog
:
<activity android:theme="@style/CustomDialogTheme">