是否有办法将一个资源包含在另一个资源中(例如,多个活动的布局中的标头设计)。我知道我可以在运行时添加它,可以在XML中完成吗?
答案 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
包含标题。
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" />