38

I want to create a UI layout in XML and have it inserted as a child into an existing view (It will be inserted multiple times).

For example, here is what the XML file will contain:

<RelativeLayout
    android:id="@+id/relativeLayout1" >
    <Button android:id="@+id/myButton"
        android:text="@string/mystring" />
</RelativeLayout>

Now I get the parent LinearLayout and now want to add that XML file as a child view, e.g:

LinearLayout linear = (LinearLayout) findViewById(R.id.myLayout);

// need to create a view object from the xml file
linear.addView(myXmlObject);

Is it possible to convert an XML resource to a view type? If so, how would I do this?

3
  • 1
    @Eric Oh wow, I missed that. But wait! Commented Dec 15, 2012 at 4:38
  • 1
    @Sam How did I even... I just... okay, you completely owned me there. Commented Dec 15, 2012 at 4:41
  • It feels to me like you you should probably looking for an Adapter of some sort. Commented Dec 15, 2012 at 5:14

1 Answer 1

102

I believe you want the LayoutInflater. Let's say your example XML is in a file custom_layout.xml:

LayoutInflater inflater = LayoutInflater.from(context);
RelativeLayout layout = (RelativeLayout) inflater.inflate(R.layout.custom_layout, null, false);

LinearLayout linear = (LinearLayout)findViewById(R.id.myLayout);
linear.addView(layout);
Sign up to request clarification or add additional context in comments.

1 Comment

How did you handle the button click? I mean each row's button click has a different function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.