一、前期基础知识储备
(1)样式Style定义,上官方文档:
Resources.Theme
This class holds the current attribute values for a particular theme. In other words, a Theme is a set of values for resource attributes; these are used in conjunction with TypedArray to resolve the final value for an attribute.
The Theme's attributes come into play in two ways: (1) a styled attribute can explicit reference a value in the theme through the "?themeAttribute" syntax; (2) if no value has been defined for a particular styled attribute, as a last resort we will try to find that attribute's value in the Theme.
You will normally use the obtainStyledAttributes(AttributeSet, int[], int, int) APIs to retrieve XML attributes with style and theme information applied.
样式Style是用来指定视图或窗口的外观和格式的一组属性集合。样式可以用来指定高度、填充、字体大小、背景颜色等等。样式在XML资源文件中定义,和指定布局的XML文件是分开的。
Android中的样式和网页设计中的CSS(层级联样式表)践行同样的哲学:将设计和内容分开。
(2)主题Theme定义,上官方文档:
R.style
public static final class R.style
extends Object
java.lang.Object
↳ android.R.style
主题Theme是应用到整个activity或者Appalachian应用程序的样式。样式只应用到单个视图。当一个样式变成主题后,Activity或应用程序中的所有视图都将应用这个样式中它所支持的属性。例如,你可以将上面例子中的GodeFont样式作为一个activity的主题,然后这个Activity中所有的文字都将变成monospace字体。
主题在应用中最常见的就是应用程序皮肤的切换,如下所示,是某网易云音乐的换肤界面,通过换不同的皮肤,读者可以看到,包括标题栏,小图标的颜色、选中字体的颜色、播放控制键的颜色都是跟随主题进行切换的。通过样式Style可单独控制其中某一个元素的属性,通过主题Theme可以实现一组元素属性的控制,我们可以称主题Theme为特殊的样式Style。
二、上代码,具体实现
(1)定义样式Style步骤:
①在res\values\ 下创建styles.xml文件;
②添加<resouces>节点(根节点);
③添加自定义的style;
④在特定控件或layout中添加style属性;
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="MyTextStyle">
<item name="android:textColor">#FF0000C0</item>
<item name="android:layout_width">wrap_content</item>
<item name="android:layout_height">wrap_content</item>
</style>
</resources>
//在布局文件中引用自定义的Style
<TextView
style="@style/MyTextStyle" />
(2)定义主题Theme步骤:
①在res\values\ 下创建themes.xml或者styles.xml文件;
②添加<resouces>节点(根节点);
③添加自定义的style;
④在AndroidManifest.xml文件中,为Activity指定theme属性
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="MyBubbleTheme" parent="@android:style/Theme.Dialog" >
<item name="android:windowBackground">@drawable/bubble</item>
</style>
</resources>
//在manifest文件中引用自定义的Theme
<activity
android:name=".BlurThemeActivity"
android:theme="@style/MyBubbleTheme" />
读者有没有注意到parent属性,<style>元素的parent属性是可选的。parent属性用来指定当前样式要继承属性的样式的id(样式之间是可以继承的)。你还可以覆写继承来的属性。
小结:Android平台提供了一大堆样式和主题,读者在开发中完全可以在你的应用程序中使用。你可以在R.style class(很多很全)中找到一份关于所有可使用的样式参考。要使用所有在这份参考中列出的样式,你需要将样式name的下划线换成点号。比如,你可以通过”@android:style/Theme.NoTitleBar“来使用这里列出的Theme_NoTitleBar主题。
三、Android系统常用自带样式
读者可参考《Android系统自带样式(@android:style/) (转)》