我發現的一個解決方案是使用attributes
,其中Theme
可以指向不同的Styles
。
attrs.xml
<resources>
<!-- Attributes referencing whatever style the theme needs to set up. -->
<attr name="main_menu_button_style_play" format="reference" />
</resources>
的themes.xml
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- App specific attributes -->
<item name="@attr/main_menu_button_style_play">@style/MainMenu.Button.Play</item>
</style>
<!-- Blue application theme. -->
<style name="AppTheme.Blue" parent="AppTheme">
<!-- App specific attributes -->
<item name="@attr/main_menu_button_style_play">@style/MainMenu.Button.Play.Blue</item>
</style>
</resources>
styles.xml
<style name="MainMenu.Button.Play">
<item name="android:background">#f76d3c</item>
<item name="android:text">PLAY</item>
</style>
<style name="MainMenu.Button.Play.Blue">
<item name="android:background">#2ca8c2</item>
</style>
activity.xml
<Button android:id="@+id/main_play_button"
style="?attr/main_menu_button_style_play"/>
這種方法非常好,並允許我在Activity.onCreate()
方法中設置Theme
。
唯一惱人的問題,我有這個解決方案是Android Studio中抱怨說,Button
缺少layout_width
,即使他們在Style
正在定義layout_height
。我想它不會通過選擇的Theme
後面的屬性參考。
我最終使用的另一種方法是更多地使用屬性。爲所有屬性值創建屬性我想在主題之間進行更改。因此,我用main_menu_button_play_background
來代替定義樣式參考的main_menu_button_style_play
。這種方法的工作量與簡單指定樣式的工作量相同,因爲主題可以繼承,但IDE可以理解它。