Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Android support layout inheritance (similar to Django templates)?

Tags:

android

django

I may be misunderstanding how <include> and <merge> work, but according to Simple example of <merge> and <include> usage in Android XML-layouts, <include> means "take that file and paste its contents here".

Let's say you want to have 3 activities that all have the same header, but have different content. You'll still need to have 3 XML layout files for each activity. The only difference between each of the layout's will be that they define a different layout in the <include> tag. If I wanted to add a footer I'd have to change each layout.

I'm looking for a way to achieve the inverse, so the children layouts would override specific blocks of the parent (similar to Django templates). That way, if I wanted to add that footer, I would just change the parent and the children would continue to override just the content.

like image 717
Brandon O'Rourke Avatar asked Dec 01 '10 22:12

Brandon O'Rourke


2 Answers

Let's say you want to have 3 activities that all have the same header, but have different content. You'll still need to have 3 XML layout files for each activity. The only difference between each of the layout's will be that they define a different layout in the tag.

If you want to have three activities that all have the same header, you will have one layout file per activity. That file will have the widgets unique to that activity, and an <include> element for the common header.

That way, if I wanted to add that footer, I would just change the parent and the children would continue to override just the content.

That is not supported by Android at this time. As janoliver indicates, you could roll your own solution for this.

like image 141
CommonsWare Avatar answered Nov 02 '22 11:11

CommonsWare


I've solved this by adding ViewStub entries into the layout xml of the parent, and - depending on the type of subclass - inflating the correct stub.

http://developer.android.com/reference/android/view/ViewStub.html

ViewStub is sort of lazy loading a view, so if you never call inflate() on it or never make it visible it won't be added to the layout hierarchy.

like image 2
Risadinha Avatar answered Nov 02 '22 09:11

Risadinha