【问题标题】:Include a second layout resource in my first one在我的第一个布局资源中包含第二个布局资源
【发布时间】:2010-10-06 12:45:46
【问题描述】:

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

【问题讨论】:

    标签: android include android-layout


    【解决方案1】:

    是的,您可以在 XML 中执行此操作。见android docs 关于合并/包含

    基本上你会有 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); 中包含标题。

    除此之外,您还可以通过编程方式做一些很酷的事情,例如将布局从 xml 插入到 root.xml(setContentView(); 之后:

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

    rootLayout 是由 id 找到的父 RelativeLayoutR.layout.home 是您希望添加到根目录的布局

    【讨论】:

      【解决方案2】:

      当然可以。查看this帖子了解详细说明:

      &lt;include android:id="@+id/my_id" layout="@layout/layout_id" /&gt;

      【讨论】:

        猜你喜欢
        • 2012-07-04
        • 1970-01-01
        • 1970-01-01
        • 2014-02-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多