安卓的styles.xml文件和theme的使用

来源:互联网 发布:小黑屋码字软件下载 编辑:程序博客网 时间:2024/05/20 15:41

styles.xml的使用


基础使用

在一些视图中,它们具有相同的属性并且相应属性具有相同的值,此时可以使用”styles.xml”来统一设定。

定义styles:

<resoures>    <style name="MyStyle">        <item name="android:textColor">@android:color/blue</item>        <item name="android:textSize">18sp</item>    </style></resources>

使用styles:

<TextView    style="@style/MyStyle"    android:text="@string/hello_world"    android:layout_width="wrap_content"    android:layout_height="wrap_content"></TextView>

styles的继承

styles支持继承,甚至支持多继承。

styles的继承方式

styles的继承方式有如下两种:

1.在style标签的属性表中添加“parent”属性。

<style name="MyStyle2" parent="@style/MyStyle">

2.使用“.”(点)运算符

<style name="MyStyle.MyStyle2">

styles继承后的使用

使用时直接引用style的name属性值

<TextView    style="@style/MyStyle2"/>

或者

<TextView    style="@style/MyStyle.MyStyle2"/>

styles和theme

styles和theme定义方法类似,使用起来也差不多,区别在于theme的作用范围较大,能更改的属性也较多

theme的定义

    <resources>        <style name="MyTheme" parent="android:Theme.Holo">            <item name="android:textColor">#00aaff</item>        </style>    </resources>

theme的使用

theme的使用和style类似,只不过theme用于定义Application或者某个Activity的theme

*在AndroidManifest.xml中使用

<application android:theme="@android:style/MyTheme">    <activity android:theme="@android:style/MyTheme"/></application>

*在Activity.java中调用

 setTheme(R.style.MyTheme);

Style和Theme的区别

1.由上述代码可看出,style主要用于view,而theme则主要用于application和activity
2.在R.attr定义中以window开头的一些属性只对theme有效。
3.如果一个应用使用了theme,同时应用下的view也使用了style,那么当theme与样式style发生冲突时,style的优先级高于主题。