views:

116

answers:

4

Hi,

I want to create an android Layout of which I want to instantiate several copies. I understand that declaring the layout in an XML will create a single instance. Is there a way to use the XML View declaration as a 'definition' rather than a 'declaration' ? Or is it possible to clone a view ?

Thanks;

+3  A: 

What do you mean by instantiate several copies? In the same activity? Or in different activities?

You can inflate a layout using the LayoutInflater. This will allow you to create multiple instances of the view in the same activity.

If you are create a list of information, where each list item has the same layout you can use a ListView, which will do the inflating for you.

Mayra
I want to create a non trivial view (with an image and some fields of text), and have several of these objects on my screen in a single activity. I will look at the LayoutInflater you have pointed to. Thanks;
Kumar
The LayoutInflater works great, Thanks a lot!
Kumar
Great, glad it worked for you. When you ask a question on Stackoverflow you should mark the correct (or most helpful) answer by clicking the checkbox next to it.
Mayra
+1  A: 

Here are some tips on reusing XML Views not sure if this is what you mean.. http://developer.android.com/resources/articles/layout-tricks-reuse.html

schwiz
Thanks, I looked at the pointer. This is still static content. I will need to generate these at run time. Is there a possibility for that?
Kumar
Its a static method so you should be ok.
schwiz
A: 

If you want to create a common template and use it in multiple screens, then declare that layout as xml and then use the LayoutInflater to add your other views to it.

I wonder if you want to use the same layout multiple no of times in same activity.

Robin
Right, I want to use the same layout multiple times in the same activity
Kumar
A: 

Ok , you can use the method inflate(int resource, ViewGroup root) of LayoutInflater. and pass null as the second parameter.

However, You should keep in mind that LayoutInflator is quite expensive and should be used as less as possible

Robin