为何小米,魅族等rom都能改变各种外观?同样是的控件,在Android2.x与Android4.x版本中ui效果却不一样?
以Button为例,在Android2.x中做出Android4.x的效果.
step1.1:打开Android SDK的子目录sdk\platforms\android-19\data\res\values中的styles.xml
1.2:搜索"Widget.Holo.Light.Button",找到<style>片段
<style name="Widget.Holo.Light.Button" parent="Widget.Button">
<item name="android:background">@android:drawable/btn_default_holo_light</item>
<item name="android:textAppearance">?android:attr/textAppearanceMediumInverse</item>
<item name="android:textColor">@android:color/primary_text_holo_light</item>
<item name="android:minHeight">48dip</item>
<item name="android:minWidth">64dip</item>
</style>
1.3:到drawable目录中找到btn_default_holo_light.xml (selector),复制到工程drawable目录下
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_window_focused="false" android:state_enabled="true"
android:drawable="@drawable/btn_default_normal_holo_light" />
<item android:state_window_focused="false" android:state_enabled="false"
android:drawable="@drawable/btn_default_disabled_holo_light" />
<item android:state_pressed="true"
android:drawable="@drawable/btn_default_pressed_holo_light" />
<item android:state_focused="true" android:state_enabled="true"
android:drawable="@drawable/btn_default_focused_holo_light" />
<item android:state_enabled="true"
android:drawable="@drawable/btn_default_normal_holo_light" />
<item android:state_focused="true"
android:drawable="@drawable/btn_default_disabled_focused_holo_light" />
<item
android:drawable="@drawable/btn_default_disabled_holo_light" />
</selector>
1.4:再到drawable-hdpi目录下把selector中引用的图片拷贝过来
step2:布局文件中拖出button控件,加上一行
android:background="@drawable/btn_default_holo_light"
经过这2步,Android2.x中的button就变成了4.x风格了.
简单总结一下:value/styles.xml中找到对应风格的属性<style name="Widget.Holo.Light.Button">,改变<item name="android:background">@android:drawable/btn_default_holo_dark</item>(seletor)中的图片,即可将外观风格改变.
思考:
表面原理:找到决定外观的属性,xml中设置属性,(覆盖)设置为新的外观
内部原理:styles.xml中有多种风格(holo.light,holo.dark等),系统theme是某种风格,所有控件就会采用某种风格的style属性
实现原理:attr中定义属性名称,theme中定义主题
从Android系统的角度看:
button为例:
attrs.xml:
<declare-styleable name="Theme">
<attr name="buttonStyle" format="reference" />
themes.xml:
Holo风格:
<item name="buttonStyle">@android:style/Widget.Holo.Button</item>
Holo.Light:
<item name="buttonStyle">@android:style/Widget.Holo.Light.Button</item>
普通风格:
<item name="buttonStyle">@android:style/Widget.Button</item>
styles.xml中:
<style name="Widget.Holo.Button" parent="Widget.Button">
<item name="android:background">@android:drawable/btn_default_holo_dark</item>
<item name="android:textAppearance">?android:attr/textAppearanceMedium</item>
<item name="android:textColor">@android:color/primary_text_holo_dark</item>
<item name="android:minHeight">48dip</item>
<item name="android:minWidth">64dip</item>
</style>
好像有点乱,时间也不早了,先来去睡觉,改天再来整理.