了解 Android 样式的工作原理可能有点混乱。
我将尝试通过一个示例来解释基本的工作流程。
假设您想知道按钮的默认背景是什么。
这可以是简单的颜色(不太可能)或可绘制对象(有许多不同类型的可绘制对象)。
Android 有主题。主题基本上定义了将哪种样式应用于哪个小部件。
因此,我们的第一步是找到默认的android主题。
您可以在android-sdk\platforms\android-15\data\res\values\themes.xml 下找到它
在这个主题文件中,搜索button。
你会发现这样的东西:
<!-- Button styles -->
<item name="buttonStyle">@android:style/Widget.Button</item>
这意味着主题将样式Widget.Button 应用于按钮。
好的,现在让我们找到样式Widget.Button。
所有默认的Android风格都定义在文件android-sdk\platforms\android-15\data\res\values\styles.xml中
现在搜索Widget.Button
你会发现这样的东西:
<style name="Widget.Button">
<item name="android:background">@android:drawable/btn_default</item>
<item name="android:focusable">true</item>
<item name="android:clickable">true</item>
<item name="android:textAppearance">?android:attr/textAppearanceSmallInverse</item>
<item name="android:textColor">@android:color/primary_text_light</item>
<item name="android:gravity">center_vertical|center_horizontal</item>
</style>
有趣的是:
<item name="android:background">@android:drawable/btn_default</item>
这意味着有一个名为btn_default 的drawable 设置为按钮背景。
现在我们需要在android-sdk\platforms\android-15\data\res 下的一个可绘制文件夹中找到一个名为btn_default.* 的文件。
这可以是图像(不太可能)或像 btn_default.xml 这样的 xml 文件。
稍微搜索一下你会找到文件android-sdk\platforms\android-15\data\res\drawable\btn_default.xml
它包含如下内容:
<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" />
<item android:state_window_focused="false" android:state_enabled="false" android:drawable="@drawable/btn_default_normal_disable" />
<item android:state_pressed="true" android:drawable="@drawable/btn_default_pressed" />
<item android:state_focused="true" android:state_enabled="true" android:drawable="@drawable/btn_default_selected" />
<item android:state_enabled="true" android:drawable="@drawable/btn_default_normal" />
<item android:state_focused="true" android:drawable="@drawable/btn_default_normal_disable_focused" />
<item android:drawable="@drawable/btn_default_normal_disable" />
</selector>
现在你必须明白这是一个可绘制的选择器(众多可绘制类型之一)。
此选择器根据按钮状态选择不同的背景。例如,如果按下按钮,则它具有不同的背景。
不让我们看一下默认状态。
<item android:state_enabled="true" android:drawable="@drawable/btn_default_normal" />
它应用了一个名为btn_default_normal的drawable。
现在我们需要找到这个可绘制对象。
同样,我们需要在android-sdk\platforms\android-15\data\res 下的一个可绘制文件夹中找到一个名为btn_default_normal.* 的文件。
这又可以是图像或 xml 文件,例如 btn_default_normal.xml。
您会在不同的可绘制文件夹中找到多个名为“btn_default_normal.9.png”的文件,用于不同的分辨率。
:) 现在您知道btn_default_normal.9.png 被设置为按钮背景。