在我的第一个布局资源中包含第二个布局资源

时间:2010-10-06 12:45:46

标签: android include android-layout

是否有办法将一个资源包含在另一个资源中(例如,多个活动的布局中的标头设计)。我知道我可以在运行时添加它,可以在XML中完成吗?

2 个答案:

答案 0 :(得分:5)

是的,您可以在XML中执行此操作。查看android docs 关于merge / include

基本上你会有1个布局(root.xml),如下所示:

<?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>

heading_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<merge
  xmlns:android="http://schemas.android.com/apk/res/android">
    <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>

所以在你的Activity setContentView(R.layout.root);中你会root.xml包含标题。

除了这个以编程方式,您还可以做一些很酷的事情,例如将xml中的布局插入setContentView();LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE); inflater.inflate(R.layout.home, rootLayout); 之后:

rootLayout

其中RelativeLayout是ID找到的父R.layout.home,而{{1}}是您希望添加到根

的布局

答案 1 :(得分:0)

当然可以。查看this帖子以获取详细说明:

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