views:

33

answers:

2

Is there a way to include one resource in another (for example a header design in multiple activities' layouts). I know I can add it at run time, can it be done in the XML?

A: 

Sure can. Check out this post for a detailed explanation:

<include android:id="@+id/my_id" layout="@layout/layout_id" />

kcoppock
+3  A: 

Yes you can do this in XML. See the android docs about merge/include

basically you would have 1 layout(root.xml) as follows:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="@+id/rootLayout"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">
  <LinearLayout
    android:id="@+id/headingLayout"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">
      <include
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        layout="@layout/heading_layout" />
  </LinearLayout>
<RelativeLayout>

and the heading_layout.xml:

<?xml version="1.0" encoding="utf-8"?>
<merge
  xmlns:android="http://schemas.android.com/apk/res/android"&gt;
    <RelativeLayout
      android:layout_width="fill_parent"
      android:layout_height="wrap_content">
        <ImageView
          android:id="@+id/titleImg"
          android:src="@drawable/bg_cell"
          android:layout_width="fill_parent"
          android:layout_height="wrap_content" />
        <TextView
          android:id="@+id/titleTxt"
          android:layout_centerInParent="true"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content" />
    </RelativeLayout>
</merge>

so in your Activity you would setContentView(R.layout.root); which would include the header.

you can also do some cool stuff in addition to this programmatically, such as inserting a layout from xml into a the root.xml(after setContentView();:

LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.home, rootLayout);

where rootLayout is the parent RelativeLayout found by id and R.layout.home is a layout you wish to add to the root

binnyb