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

Bry*_*eld 2 android include android-layout

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

jam*_*mes 5

是的,你可以用XML做到这一点.查看 关于merge/include 的 android文档

基本上你会有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>
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

所以在你的ActivitysetContentView(R.layout.root);将包括标题.

除了这个以编程方式之外你还可以做一些很酷的东西,比如从xml插入一个布局到root.xml(之后setContentView();:

LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.home, rootLayout);
Run Code Online (Sandbox Code Playgroud)

id找到rootLayout的父级在哪里,是您希望添加到根目录的布局RelativeLayoutR.layout.home