Reputation: 9212
Android's <include />
element allows you to include other XML layouts. Useful for a common header across several activities.
But, what if you want to include a layout several times in the same view? For instance, I have a carefully crafted layout that I want to display three times in my view. Every of those instances would need different values. Since the include
is basically a take that XML and paste it here, I'd need something more powerful.
Is there some mechanism to do this?
(Did I explain myself correctly?)
Upvotes: 29
Views: 11882
Reputation: 3088
A blog post at http://www.coboltforge.com/2012/05/tech-stuff-layout/ (which is offline now but can be found at https://web.archive.org/web/20160425233147/http://www.coboltforge.com/2012/05/tech-stuff-layout/) explains exactly that problem (the same layout XML included several times) and how to solve it!
When you search by id you always find the first items, so the second widgets are hidden.
However, it can be solved
<include> -- id1
-- stuff
</include>
<include> -- id2
-- stuff
</include>
So we can find the subelements, by first looking up id2 / id1.
View include_1 = findViewById(R.id.id1);
View include_2 = findViewById(R.id.id2);
and finally
include_2.findViewById(R.id.elementx );
Upvotes: 59
Reputation: 19769
Another way to go could be setting the "template" layout in an xml and inflate it with LayoutInflater and add to your view as many times as you need and insert there the custom values in each one. Here is an example for Creating a Custom Toast View with Layout inflater.
Upvotes: 3
Reputation: 207863
You can use android:id
to specify the id of the root view of the included layout; it will also override the id of the included layout if one is defined. Similarly, you can override all the layout parameters.
Based on the provided android:id
you can get the section by id, and then you can again get element by id based on the section you just retrieved. This way you will be able to lookup all child views with same ids, in each parent different id views in two steps.
Upvotes: 2
Reputation: 1006614
Is there some mechanism to do this?
Create a custom View
. Here is a project where I have a ColorMixer
custom widget, for example. You could include several such ColorMixers
in one activity layout, if you so chose to. Each can have its own parameters to tailor its operation.
Upvotes: 5