写在最前面的话:Theme就是Style,只不过Style应用到Activity和Application中就不叫Style了,它叫Theme
那么style和theme到底是什么,我们在实际的应用项目又该如何应用呢?不用着急,接下来和我一探究竟。
Style
我们首先看下面代码片段
<TextView
android:textColor="#00FF00"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
使用style后
<TextView
style="@style/TextView_Style"
android:text="TextView"
/>
当然两者的效果是相同的,我们只是定义了一个文件,把相应的属相放在那个文件当中,这样我们就可以把一个style应用到各种组件当中,当然组件会选择性接受相应的属性,至于为什么这个我在后面会讲。那么我们该如何定义一个Style呢?看下面代码
在res/values的styles.xml文件中写下如下代码
<resources xmlns:android="http://schemas.android.com/apk/res/android">
<style name="TextView_Style" parent="@android:style/TextAppearance.Medium">
<item name="android:layout_height">wrap_content</item>
<item name="android:layout_width">wrap_content</item>
<item name="android:textColor">#00FF00</item>
</style>
</resources>
item当中的parent
我们注意到parent这个属性,和Java当中的类继承一样,style也有继承关系,这句话的意思就是我的父style是TextAppearance.Medium。如果我们在子style定义和父style相同的<item>
,组件会应用子style的。这就给我们一个很大的权限,我们可以继承系统提供好的style,而我们可以继承和更改相应的属性。是不是很棒。
继承自己写的style
那么我们如何继承我们自己的style呢?比如说上面的TextView_Style看下面代码
<resources>
<style name="TextView_Style.CodeFont">
...
</style>
</resources>
Style 的那些属性
style的item到底可以写那些属性,这个我们可以找到他们自己对应的类中,比如说<TextView>
,我们可以直接找到他对应的TextView的类,然后打开文档,找到里面的 TextView XML attributes,如下图
上面的这些属性都可以应用到TextView当中,如果我们把一个属性应用到一个不支持这个属性的组件当中,是没有关系的。如果你想看所有可用的属性,打开文档搜索R.attr
Theme
看下面代码
<application android:theme="@style/CustomTheme">
就想我开头讲的那样,这个就是传说中的Theme,其实他就是style。
Activity是相同的,我们需要注意的是下面两种Theme。
<activity android:theme="@android:style/Theme.Dialog">
<activity android:theme="@android:style/Theme.Translucent">
第一种是把activity的样式设置为对话框样形式,第二种是把activity设置为半透明形式。
安卓平台为我们提供了大量的theme和style,不同的平台是可以支持不同的theme,安卓会根据版本的不同进行选择,我们只需要按照他的要求定义好就行了,比如说安卓3.0以上的,我们可以声明一个values-v11文件夹,写上相应的style。
如果将一个style应用到一个ViewGroup当中,子View是不会继承相应的属性,但是如果将一个style作为一个theme应用到一个ViewGroup中(Activity或者Application),结果则是相反的
————————————————————————
有问题欢迎留言提问