本文主要是介绍Android 2.2 API demos -- theme style,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
style和theme的概念
现在借鉴官方的文档,总结一下style和theme的相关概念。
style是一个包含一种或者多种格式化属性的集合,可以将其作为一个单位用在layout XML的单个view上。 比如,可以定义一种style来规定文本的文字大小和颜色,然后将其应用于一个特定的view。
theme是一个包含一种或者多种格式化属性的集合,可以将其作为一个单位用在整个application或者其中某个activity上。比如,可以定义一个theme,其中定义的文字的大小和颜色,然后将其应用于某个activity,那么这个activity中的所有文本就都是这种样式了。
定义style
1. 在res/values/目录下新建一个XML文件。
2. XML文件的大体格式如下,根节点是<resources>,每一个style对应一个<style>元素,style里的每一种格式化属性对应一个<item>元素。
<?xml version="1.0" encoding="utf-8"?><resources><style name="ImageView240dpi"><item name="android:src">@drawable/stylogo240dpi</item><item name="android:layout_width">wrap_content</item><item name="android:layout_height">wrap_content</item>
</style>
</resources>
3. item的值可以是fill_parent等关键字,也可以引用其它的资源类型,例如,
<?xml version="1.0" encoding="utf-8"?><resources><style name="CustomTheme"><item name="android:windowNoTitle">true</item><item name="windowFrame">@drawable/screen_frame</item><item name="windowBackground">@drawable/screen_background_white</item><item name="panelForegroundColor">#FF000000</item><item name="panelBackgroundColor">#FFFFFFFF</item><item name="panelTextColor">?panelForegroundColor</item><item name="panelTextSize">14</item><item name="menuItemTextColor">?panelTextColor</item><item name="menuItemTextSize">?panelTextSize</item></style></resources>
用@符号和?符号来引用资源。@表明我们引用的资源是其它地方定义过的(也许在这个项目中或者在Android框架中)。?表明我们引用的资源的值在当前加载的主题中。这通过以名字引用特定的<item>来完成(比如,panelTextColor使用了分配给panelForegroundColor的相同颜色)。这种技巧只能用在XML资源当中。
4. <style>中的parent属性可以使一个style继承另一个style的属性。
既可以继承Android平台上的预定义style:
<style name="GreenText" parent="@android:style/TextAppearance"><item name="android:textColor">#00FF00</item>
</style>
又可以继承自己定义的style,当继承自己定义的style时,可以不使用parent属性,只需要在name里加上被继承的style的name作为前缀即可:
<style name="GreenText.Red" parent="@android:style/TextAppearance"> <item name="android:textColor">#FF0000</item>
</style>
使用style
1. 将style使用在view上。
<TextView style="@style/GreenText.Red" android:text="@string/hello" />
2. 将style应用在activity上。
见官方custom dialog示例。
<activity android:name=".app.CustomDialogActivity"android:label="@string/activity_custom_dialog"android:theme="@style/Theme.CustomDialog"><intent-filter><action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.SAMPLE_CODE" /></intent-filter>
</activity>
3. 将style应用在application上。
<application android:name="ApiDemosApplication"android:label="@string/activity_sample_code" android:theme="@style/Theme.CustomDialog"android:icon="@drawable/app_sample_code">
4. 在Java代码中应用style。
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ... setTheme(android.R.style.Theme_Light); setContentView(R.layout.main);}
5. 当你将一个style应用在viewgroup上时,它的内部view不会继承这些样式。
这篇关于Android 2.2 API demos -- theme style的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!