learner
learner

Reputation: 11780

Combine multiple xml files into one final android layout

Say I have a layout file that I would like to use as part of another layout, how would I do that?

For example, I have a table layout at /res/layout/table.xml. I want to use that table as a component inside a relative layout at /res/layout/relative_stuff.xml. Say my relative layout is to contain the table and two buttons.

The simple case is to do the combination completely inside the relative_stuff.xml file. But a better case would be the ability to set the table xml programmatically: the reality is I want to choose from many different tables, for now say two tables at: /res/layout/table_1.xml and /res/layout/table_2.xml.

So basically my main layout file is /res/layout/relative_stuff.xml. And I want to set either of two tables inside it programmatically.

Upvotes: 1

Views: 7943

Answers (2)

Gaurang Agarwal
Gaurang Agarwal

Reputation: 66

You can use Layout Inflator Service to add multiple add the activity.

Upvotes: 0

Bryan Herbst
Bryan Herbst

Reputation: 67189

You an re-use layouts using an include tag.

For example, using your example layout/table.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" 
    android:layout_width=”match_parent”
    android:layout_height=”match_parent”>

    <include layout="@layout/table"/>

</LinearLayout>

If you don't want to do it in XML, you can use a LayoutInflater to inflate your XML and add it to whatever container you are using.

LayoutInflater mLayoutInflater = (LayoutInflater) context.getSystemService(LAYOUT_INFLATER_SERVICE);
View tableLayout = mLayoutInflater.inflate(R.layout.table, (ViewGroup) findViewById(R.layout.root_id));
rootLayout.addView(tableLayout);

Upvotes: 5

Related Questions