Android:如何动态包含XML布局?

时间:2010-10-28 19:51:16

标签: android layout android-layout include

我想将我的UI分解为多个XML布局。第一个是主要布局,其他布局是内容布局。

我希望能够设置在运行时动态包含哪个content_layout,所以我不想在我的XML文件中设置"layout="@+layout/content_layout"

以下是我的布局:

main_layout.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="600dp"
    android:layout_height="800dp" >

    <TextView
        android:id="@+id/title"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true" />

    <include /> <!-- I WANT TO INCLUDE MY CONTENT HERE -->

    <Button
        android:id="@+id/cancelButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:text="Cancel" />

</RelativeLayout>

content_layout.xml:

<?xml version="1.0" encoding="utf-8"?>
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/whatever"
    android:layout_height="wrap_content"
    android:layout_width="fill_parent" />

content_layout2.xml:

<?xml version="1.0" encoding="utf-8"?>
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/whatever2"
    android:layout_height="wrap_content"
    android:layout_width="fill_parent" />

我该怎么做?

谢谢!

2 个答案:

答案 0 :(得分:38)

<RelativeLayout android:id="@+id/rl" ...

在您的代码中:

// get your outer relative layout
RelativeLayout rl = (RelativeLayout) findById(R.id.rl);


// inflate content layout and add it to the relative layout as second child
// add as second child, therefore pass index 1 (0,1,...)

LayoutInflater layoutInflater = (LayoutInflater) 
        this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);    
rl.addView(1, layoutInflater.inflate(R.layout.content_layout, this, false) ); 

答案 1 :(得分:5)

您可以尝试使用ViewStub,只需更改以编程方式扩展的布局。

This answer discusses using one ViewStub.