tags:

views:

700

answers:

3

Hi,

I have a layout defined in XML. It contains also:

<RelativeLayout
    android:id="@+id/item"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
/>

I would like to inflate this RelativeView with other XML layout file. I may use different layouts depending on a situation. How should I do it? I was trying different variations of

RelativeLayout item = (RelativeLayout) findViewById(R.id.item);
item.inflate(...)

But none of them worked fine. Heeelp ;)

+1  A: 

You inflate an XML resource. See the LayoutInflater doc .

If your layout is in a mylayout.xml, you would do something like:

View view; 
LayoutInflater inflater = (LayoutInflater)   getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
view = inflater.inflate(R.layout.mylayout, null);

RelativeLayout item = (RelativeLayout) view.findViewById(R.id.item);
ccheneson
I have my main view inflated. The problem is I want to inflate part of it from other XML file. This item RelativeLayout is part of bigger layout and I want to fill it with layout from another XML file.
Michal Dymel
hum I m sorry then I have no clue :( . Are you using something like <include> in your main view to include other layout?
ccheneson
No, it's simple layout. I think I will just add my elements programatically - without XML. Thanks for help!
Michal Dymel
+2  A: 

I'm not sure I have followed your question- are you trying to attach a child view to the RelativeLayout? If so you want to do something along the lines of:

RelativeLayout item = (RelativeLayout)findViewById(R.id.item);
View child = getLayoutInflater().inflate(R.layout.child);
item.addView(child);
Jack Patmos
I get an error: 02-25 22:21:19.324: ERROR/AndroidRuntime(865): Caused by: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
Michal Dymel
A: 

It's helpful to add to this, even though it's an old post, that if the child view that is being inflated from xml is to be added to a viewgroup layout, you need to call inflate with a clue of what type of viewgroup it is going to be added to. Like:

View child = getLayoutInflater().inflate(R.layout.child, item, false);

The inflate method is quite overloaded and describes this part of the usage in the docs. I had a problem where a single view inflated from xml wasn't aligning in the parent properly until I made this type of change.

Maximus