感谢wingman the hint。我的情况涉及颜色,这有点复杂,所以我会在这里写下我的解决方案。
我有两个主题(浅色和深色),用户可以在“设置”屏幕中进行选择。我有一个ListView,它可以有两种类型的行(普通行和注释行),每种行都有自己的样式。首先,每个布局都需要指向一个样式:
<TextView style="@style/PlainItemText" ... />
(或NoteItemText)我们需要定义样式:
<style name="PlainItemText">
<item name="android:textSize">@dimen/list_item_font_size</item>
<item name="android:textStyle">bold</item>
<item name="android:textColor">?plainTextColor</item>
</style>
文本颜色无法固定,因为它取决于所选主题。我们必须创建一个自定义属性并用问号引用它,如上所述。我们在res/values/attrs.xml中定义属性:
<!-- Attributes we use to set the text color of the various list items. -->
<attr name="plainTextColor" format="reference|color"/>
<attr name="noteTextColor" format="reference|color"/>
然后我们可以定义各种颜色。这里我们有两个样式和两个主题,所以我们需要四个颜色状态列表,每个都在res/color 下的自己的文件中。例如,这里是res/color/plain_text_color_dark.xml:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_window_focused="false" android:color="@android:color/white"/>
<item android:state_selected="true" android:color="@android:color/black"/>
<item android:state_focused="true" android:color="@android:color/black"/>
<item android:state_pressed="true" android:color="@android:color/black"/>
<item android:color="@android:color/white"/>
</selector>
所有这些文件中选择/聚焦/按下的颜色都是相同的,因为它们超出了突出显示的颜色。小心state_window_focused 版本。它的行为不像宣传的那样,在所有情况下我都必须将其设置为默认颜色(上面的最后一行)。现在我们需要创建主题并将属性绑定到其中一种颜色。这些行进入res/values/themes.xml:
<style name="Theme.Dark" parent="android:Theme">
<item name="plainTextColor">@color/plain_text_color_dark</item>
<item name="noteTextColor">@color/note_text_color_dark</item>
</style>
<style name="Theme.Light" parent="android:Theme.Light">
<item name="plainTextColor">@color/plain_text_color_light</item>
<item name="noteTextColor">@color/note_text_color_light</item>
</style>
最后,我们在运行时选择一个主题,在 Activity 的 onCreate() 方法中,在调用super.onCreate()之前:
if (isDarkTheme) {
activity.setTheme(R.style.Theme_Dark);
} else {
activity.setTheme(R.style.Theme_Light);
}
请注意,我没有考虑 Holo 等较新的主题,因此我的应用在 Honeycomb 及更高版本上看起来很旧。我会在某个时候解决这个问题,但这不是回归。
在我的例子中,一个转折是一些活动有一个更大的标题栏以适应一些按钮。原则上我应该创建四个主题,一个用于窄标题的明暗和一个用于胖标题的明暗。但相反,我创建了一种混合风格:
<!-- Mix-in style for activities. -->
<style name="ButtonTitleBar">
<item name="android:windowTitleSize">44dp</item>
</style>
并按程序将其添加到我正在使用的任何主题中。这段代码紧跟在上述setTheme() 调用之后:
if (buttonTitleBar) {
// Mix in this other style.
Resources.Theme theme = activity.getTheme();
theme.applyStyle(R.style.ButtonTitleBar, true);
}
我没有在任何地方看到这个记录,我不知道它是否合法,但Activity.getTheme() 的代码暗示它应该可以正常工作,并且它在我的所有测试中都有效。这有助于避免您可以在标准 Android 主题列表中找到的主题组合爆炸式增长。