您的位置:首页 > 移动开发 > Android开发

Android中的风格和主题(style和theme)

2014-03-12 21:56 357 查看
style 和 theme 其实在意义上没有什么不同,他们都是一组UI属性的定义集合。而他们中间的区别就是作用的范围而已,还有一些在 theme 可以设置但是在 style 不能设置的属性。一.style 和 theme 的区别因为开始使用 style 和 theme 时一般比较困惑他俩到底有什么不同,所以在这里就先介绍一下 style 和 theme 的不同吧:style: 针对一些特定的具体的组件,例如TextView、EditText、ImageButton等。他们都是某个 activity 中的控件theme:  用来设置 activity 或 application 的样式,如果设置了的话,那么这个 activity 或者整个儿 app 中的控件都会使用 theme 中定义的UI属性二.style 和 theme 的创建style 和 theme 的创建方法都是一样的,只是引用他们的时候用的xml标签不一样,所以这里以style 的创建方法做样例,至于引用的区别下边也会给出。style和theme都是作为一种资源文件而存在的,所以要把内容写在xml文件中并放在工程目录中的 
res/values/ 
目录下,定义
style 会用到如下几个标签:
(1)<resources>:
这个标签必须作为该style xml文件的根标签
(2)<style>:
这个标签必须在<resources>标签的内部,用来定义style,可以设置这个标签的name属性来定义style的标识符,也就是说你要用这个style的时候要通过name属性的值来找到并引用它。
(3)<item>:
这个标签必须在<style>标签的内容,用来定义相应属性的值,例如我们最常见的android:layout_width可以被这么定义<item name="android:layout_width">fill_parent</item>。
下面给出一个样例文件,文件路径+文件名为 res/values/mystyle.xml:
<?xml version="1.0" encoding="UTF-8"?><resources><style name="customStyle"><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:textSize">24sp</item></style></resources>
三.style 和 theme 的使用那么定义好的 style 如何使用呢?可以在需要用到的地方这样设置它,以一个TextView控件来示范:
<TextViewstyle="@style/customStyle"     <!-- customStyle就是上面mystyle.xml中style标签里的name的值 -->android:text="@string/hello_world" />
如果想要把它用作 theme,那么就需要在 AndroidManifest.xml 的 <application> 或 <activity> 标签中来设置:
<applicationandroid:allowBackup="true"android:icon="@drawable/ic_launcher"android:label="@string/app_name"android:theme="@style/customStyle" >……</application>
<activityandroid:name="com.example.testapp.MainActivity"android:theme="@style/customStyle"android:label="@string/app_name" >……</activity>
四.继承的使用如果你并不想要完全重新定义一组UI,而是希望扩展之前实现过的或是SDK自带的一套 style 和 theme ,那么就可以使用接下来这种继承的方法。继承的方式有两种:(1)  通过设置<style>标签中的 parent 属性来指定父style:
<style name="customStyle"><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:textSize">24sp</item></style><style name="customStyle2" parent="@style/customStyle">  <!-- 通过parent属性来指定父style --><item name="android:textColor">#FF0000</item></style>
(2) 通过给<style>中的name属性添加前缀来指定父style:
<style name="customStyle"><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:textSize">24sp</item></style><style name="customStyle.customStyle2">   <!-- 通过添加前缀来指定父style --><item name="android:textColor">#FF0000</item></style>
注意1:派生的style中定义的属性会覆盖父style中已经定义了的属性注意2:如果是继承SDK自带的style或者theme,那么就必须使用设置parent属性的方法来实现,不能用加前缀的方法如果转载请注明出处:http://blog.csdn.net/gophers/article/details/21119667
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  编程 Android 控件 界面