bamboo10
bamboo10

Reputation: 133

Android cascading layouts?

Is there a way to specify different styles for different elements of a view group within one style?

For example, I have a list where each item has a title, details and separator. I would like to be able to have one style tag in my styles.xml that applies side padding to the text but only top/bottom padding to the separator.

I realise my thinking could be influenced by css, I was just wondering if there was an elegant solution in android for it.

Upvotes: 1

Views: 1310

Answers (3)

Nelson Wright
Nelson Wright

Reputation: 506

If it's just your own styles you want to extend, then you can use the dot notation, as mentioned in the Android docs, i.e. you could do:

<style name="ListItemSeparator">
    <item name="android:background">?android:attr/listDivider</item>
    <item name="android:layout_height">1px</item>
</style>
<style name="ListItemSeparator.LastListItemSeparator">
    <item name="android:layout_marginBottom">20dp</item>
</style> 

Then reference the style like:

<View style="@style/ListItemSeparator.LastListItemSeparator"/>

Upvotes: 2

bamboo10
bamboo10

Reputation: 133

A style can have a parent, with the resulting view applying attributes "top-down", i.e. the child styles will override conflicting parent style attributes.

Code I ended up using (I have a list with multiple separators, I wanted padding only on the last one):

<style name="ListItemSeparator">
    <item name="android:background">android:attr/listDivider</item>
    <item name="android:layout_height">1px</item>
</style>
<style name="LastListItemSeparator" parent="ListItemSeparator">
    <item name="android:layout_marginBottom">20dp</item>
</style>  

More info can be found here

Upvotes: 2

wvdz
wvdz

Reputation: 16641

You can subclass a View in java and then refer to it in your xml.

Then, you can subclass your custom View to create views that inherit from it.

Upvotes: 1

Related Questions