style 是属性的集合,用于指定视图的外观和格式。样式可以指定高度、填充、字体颜色、字体大小、背景颜色等属性。
例如,通过使用样式,您可以采用这种布局 XML:
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#00FF00"
android:typeface="monospace"
android:text="@string/hello" />
然后把它变成这样:
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="@style/CodeFont"
android:text="@string/hello" />
与样式相关的属性已从布局 XML 中删除,并放入名为 CodeFont 的样式定义中,然后使用 android:textAppearance 属性应用。
要创建 CodeFont 样式,请将 XML 文件保存在项目的 res/values/ 目录中。这是一个例子:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="CodeFont" parent="@android:style/TextAppearance.Medium">
<item name="android:textColor">#00FF00</item>
<item name="android:typeface">monospace</item>
</style>
</resources>
此示例样式可以从 XML 布局中引用为 @style/CodeFont,如上面的 TextView 所示。 主题就是风格。唯一的区别是主题是应用于整个 Activity 或应用程序的样式,而不是单个视图。
当一个样式被应用为主题时,活动或应用程序中的每个视图都会应用它支持的每个样式属性。例如,如果您将相同的 CodeFont 样式应用为活动的主题,则该活动内的所有文本都以绿色等宽字体显示。
<resources>
<style name="AppTheme" parent="Theme.Material">
<item name="colorPrimary">#673AB7</item>
<item name="colorPrimaryDark">#512DA8</item>
<item name="colorAccent">#FF4081</item>
</style>
</resources>
以下示例说明了使用引用为同一属性指定值:
<resources>
<style name="AppTheme" parent="Theme.Material">
<item name="colorPrimary">@color/primary</item>
<item name="colorPrimaryDark">@color/primary_dark</item>
<item name="colorAccent">@color/accent</item>
</style>
</resources>
要为应用程序的所有活动设置主题,请打开 AndroidManifest.xml 文件并编辑标签以包含带有样式名称的 android:theme 属性。例如:
<application android:theme="@style/CustomTheme">
如果您希望仅将主题应用于应用中的一个活动,则将 android:theme 属性添加到标签中。
正如 Android 提供其他内置资源一样,您可以使用许多预定义的主题,以避免自己编写它们。例如,您可以使用 Dialog 主题并使您的活动看起来像一个对话框:
<activity android:theme="@android:style/Theme.Dialog">
或者如果您希望背景透明,请使用半透明主题:
<activity android:theme="@android:style/Theme.Translucent">