在Android中有一种类似于HTML和CSS将样式和内容分离的机制。我们可以将内容定义在layout的XML中,将样式定义在style的XML中。通过HTML和CSS的实践证明,这种分离更有益于代码的重用和维护。
Custom Dialog示例
Android官方API Demo中的Custom Dialog就是一个简单的示例。
首先,将样式(style)定义在res/values/styles.xml中。
<style name="Theme.CustomDialog" parent="android:style/Theme.Dialog">
<item name="android:windowBackground">@drawable/filled_box</item>
</style>
其次,将内容(layout)定义在res/layout/custom_dialog_activity.xml中。
<?xml version="1.0" encoding="utf-8"?> <!-- This screen consists of a single text field that displays some text. --> <TextView xmlns:android=http://schemas.android.com/apk/res/android android:id="@+id/text" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center_vertical|center_horizontal" android:text="@string/custom_dialog_activity_text"/>
第三,将样式应用到内容上,见AndroidManifest.xml。 将Activity的theme属性配置成想要的style。
<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>
在官方的示例中,一个style被应用在一个activity上了,其实一个style还可以被应用在view或者整个application上。如果将一个style应用在activity或者application上,那么这个style就被称作是theme。
Android样式与主题
本文介绍Android中如何使用样式和主题来分离布局与表现,通过一个CustomDialog实例详细展示了如何定义和应用样式,以及如何在不同层级(View、Activity、Application)上使用主题。
2万+

被折叠的 条评论
为什么被折叠?



