Android style inheritance

别来无恙 提交于 2021-01-28 19:27:46

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!