Android的风格设计(style)是一个很重要的功能,因为它可以让应用程序里的控件(widget)个性化。风格设计的使用如下:
- 在Android的项目里以XML的资源来定义风格
- 一个Android项目可以定义多个风格
- 让widget套用其中的一个样式
Android的style功能,主要的对象是widget,风格是为了套用到widget上;另外Android提供布景(theme)功能,可以做更大范围的套用。相关阅读:Android的布景设计(theme) http://www.linuxidc.com/Linux/2012-05/61361.htm
Android事件监听器(Event Listener) http://www.linuxidc.com/Linux/2012-05/61186.htm下面是一个风格定义的具体例子:在/res/values/目录下建立一个新文件style.xml,编辑内容如下:
- <?xml version="1.0" encoding="utf-8"?>
- <resources>
- <style name="myText">
- <item name="android:textSize">18sp</item>
- <item name="android:textColor">#00FF00</item>
- </style>
- <style name="myButton">
- <item name="android:background">#00BFFF</item>
- </style>
- </resources>
style.xml语法说明:
- 在<resource>标签定义资源项目,<style>标签用来定义风格资源;
- <style>的name属性定义风格名称,widget使用此名称套用;
- <item>标签定义此风格的内容;
- textSize —— 字体大小
- textColor —— 字体颜色
- background —— 背景
- 更多,参考Android Reference
定义好style后,就可以让widget套用。让widget套用定义好的style方法很简单,只需在main.XML中的widget项目属性添加定义好的style name就可以了,编辑main.XML:
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:orientation="vertical" >
-
- <TextView
- style="@style/myText"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="@string/hello" />
-
- <Button
- android:id="@+id/btn"
- style="@style/myButton"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content" />
-
- </LinearLayout>