1、Style和Theme的异同
区别:
Style:Style是作用于控件级别的,通常应用于某个控件,一个View只能使用一个Style,如果View包含子View,Style对子View也是无效的,它只对当前View有效
Theme:Theme是作用于Activity或Application的,作用于单个Activity或所有Activity,不能作用于单独某个控件
即Style是局部的,而Theme是全局的
相同点:
都位于values文件夹下的style.xml,定义的方法一样,均是对ui进行控制的多个属性
2、定义Style文件
e.g
<style name="Widget.Plaid.Button.InlineAction" parent="…">
<item name="android:gravity">center_horizontal</item>
<item name="android:textAppearance">@style/TextAppearance.CommentAuthor</item>
<item name="android:drawablePadding">@dimen/spacing_micro</item>
</style>
定义 style 的 xml 文件必须以<resources>为根节点,其中:
style中name定义名字,parent定义继承自哪个父style,item设置具体style属性
3、继承
style的继承有两种方式,分别是 ** .继承 **
<style name="parent.childe">
和指定parent属性
<style name="childe" parent="@style/parent">
如果style中有两个继承,那么执行顺序为:
.继承->parent继承->子定义
以下截自:android Theme Style 两种继承方式 以及优先级
在2种继承方式都使用的情况下
1.首先子样式继承 以 .(点方式) 继承的父样式
2.接下来继承 以 parent 指定的父样式,并且如果有相同的属性,则覆盖 1. 中已经继承下来的样式
3.最后在 2. 的基础上 ,再次将子元素定义的样式覆盖一次,得到最终效果
4、使用
1、Style
使用Style时,如需对TextView定义为CodeFont样式:
<TextView
style="@style/CodeFont"
android:text="hello world"/>
style 只对直接应用的节点起作用,如果 style 用于 ViewGroup,那么该 style 只对 ViewGroup 起作用,对子 View不起作用。
2、Theme
Theme应用于整个Application,我们需要在AndroidManifest.xml文件中,为Application标签增加android:theme属性,并指定为特定的style
<application android:theme="@style/CustomTheme"></application>
5、从Context获取Style和Theme
obtainStyledAttributes(返回TypedArray)
public TypedArray obtainStyledAttributes(AttributeSet set, int[] attrs, int defStyleAttr, int defStyleRes)
该方法是Context类为我们提供的获取style中特定属性值的方法。通过这个方法,我们就可以获取在style中定义的各种属性值,然后根据获取到的不同的属性值实现差异化的效果。
参数:
AttributeSet: 属性的基本集,可能为空
attrs: 要检索的所有属性
defStyleAttr:defStyleAttr参数是当前theme下定义的一个style资源的属性,并为最后生成的TypedArray资源数组提供了默认值的功能
defStyleRes:一个style资源的引用来为View提供属性默认值。但是优先级较低
getTheme:
getTheme()方法可通过getTheme().resolveAttribute(R.attr.xxx, typedValue, true)获取对应属性