问题
I have two themes, one has ActionBar and one without. It seems redundant to do duplicate the styles, is there any way to simplify it?
Thanks
<style name="AppTheme.NoActionBar" parent="Theme.AppCompat.Light.NoActionBar">
<item name="colorPrimary">@color/primary_color</item>
<item name="android:windowBackground">@color/bg_color</item>
<item name="colorAccent">@color/accent_color</item>
<item name="colorPrimaryDark">@color/darker_color</item>
<!-- Button style -->
<item name="android:buttonStyle">@style/ButtonStyle</item>
<item name="buttonStyle">@style/ButtonStyle</item>
</style>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="colorPrimary">@color/primary_color</item>
<item name="android:windowBackground">@color/bg_color</item>
<item name="colorAccent">@color/accent_color</item>
<item name="colorPrimaryDark">@color/darker_color</item>
<!-- Button style -->
<item name="android:buttonStyle">@style/ButtonStyle</item>
<item name="buttonStyle">@style/ButtonStyle</item>
</style>
<style name="ButtonStyle" parent="Widget.AppCompat.Button">
<item name="android:background">@color/primary_color</item>
</style>
回答1:
Unfortunately, due to the way that Style/Theme inheritance works, there is no way around this. You could read more about that here:
Android Styles heritage
One option, however, would be to copy the contents of the NoActionBar theme. It turns out that it only contains 2 lines:
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
So your code would look like this
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="colorPrimary">@color/primary_color</item>
<item name="android:windowBackground">@color/bg_color</item>
<item name="colorAccent">@color/accent_color</item>
<item name="colorPrimaryDark">@color/darker_color</item>
<!-- Button style -->
<item name="android:buttonStyle">@style/ButtonStyle</item>
<item name="buttonStyle">@style/ButtonStyle</item>
</style>
<!-- NoActionBar theme -->
<style name="AppTheme.NoActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
</style>
Now you are inheriting the AppTheme attributes as well as getting the NoActionBar behavior. Obviously this is not foolproof if the attributes of NoActionBar change in the future, but it might be a good option for someone with many attributes in their base AppTheme.
来源:https://stackoverflow.com/questions/32648464/android-style-inheritance