【发布时间】:2010-10-06 12:45:46
【问题描述】:
有没有办法将一个资源包含在另一个资源中(例如,多个活动布局中的标题设计)。我知道我可以在运行时添加它,可以在 XML 中完成吗?
【问题讨论】:
标签: android include android-layout
有没有办法将一个资源包含在另一个资源中(例如,多个活动布局中的标题设计)。我知道我可以在运行时添加它,可以在 XML 中完成吗?
【问题讨论】:
标签: android include android-layout
是的,您可以在 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 找到的父 RelativeLayout,R.layout.home 是您希望添加到根目录的布局
【讨论】:
当然可以。查看this帖子了解详细说明:
<include android:id="@+id/my_id" layout="@layout/layout_id" />
【讨论】: