NPike
NPike

Reputation: 13254

styles multiple inheritance

Is there any way to make a style inherit from multiple other styles, instead of just being limited to:

<style name="WidgetTextBase">
    <item name="android:typeface">serif</item>
    <item name="android:textSize">12dip</item>
    <item name="android:gravity">center</item>
</style>

<style name="BOSText" parent="WidgetTextBase">
    <item name="android:textColor">#051C43</item>
</style>

I would like BOSText to also inherit from:

<style name="WidgetTextHeader">
    <item name="android:textStyle">bold</item>
<style>

Upvotes: 53

Views: 22526

Answers (4)

Jonas
Jonas

Reputation: 2126

Styles do not support multiple inheritance (at least not as of Android 3.2).

The official docs say:

If you use the dot notation to extend a style, and you also include the parent attribute, then the parent styles override any styles inheritted through the dot notation.

Upvotes: 43

Ivan Syabro
Ivan Syabro

Reputation: 155

For those who was looking for solution to just merge multiple different styles into one, you can use

public void applyStyle (int resId, boolean force)

https://developer.android.com/reference/android/content/res/Resources.Theme#applyStyle(int,%20boolean). And apply it that way

context.theme.applyStyle(R.style.MyAdditionalStyle, false)

Whenever you specify true as second argument, it overrides existing values in your theme, and when false it adds only non-overlapping values from R.style.MyAdditionalStyle

I haven't tested scenario with multiple styles yet, but according to docs you can achieve it. So that's how this approach can be used as an alternative to multiple inheritance.

Upvotes: 5

Captain Kenpachi
Captain Kenpachi

Reputation: 7215

You can only inherit one style. However, you can also make the inherited style inherit from another style, and so on:

<style name="WidgetTextBase">
    <item name="android:typeface">serif</item>
    <item name="android:textSize">12dip</item>
    <item name="android:gravity">center</item>
</style>

<style name="WidgetTextHeader" parent="WidgetTextBase">
    <item name="android:textStyle">bold</item>
</style>

<style name="BOSText" parent="WidgetTextHeader">
    <item name="android:textColor">#051C43</item>
</style>

You can't inherit more than one style, but you can set up an inheritance chain.

Upvotes: 11

f0ster
f0ster

Reputation: 558

There is a parent attribute on the style tag that should let you inherit from other styles...

i.e.

<style name="CodeFont" parent="@style/WidgetTextBase">
   <item name="android:textStyle">bold</item>
</style>

http://developer.android.com/guide/topics/ui/themes.html

Upvotes: -4

Related Questions