代码之家  ›  专栏  ›  技术社区  ›  nbarraille

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

  •  35
  • nbarraille  · 技术社区  · 14 年前

    我想把我的UI分解成几个XML布局。第一个是主布局,另一个是内容布局。

    "layout="@+layout/content_layout" 在我的XML文件中。

    以下是我的布局:

    主布局.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>
    

    <?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 回复  |  直到 13 年前
        1
  •  39
  •   Mathias Conradt    14 年前
    <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) ); 
    
        2
  •  5
  •   Community CDub    8 年前

    你可以尝试使用 ViewStub 只要改变它的布局,它将充气程序。

    This answer discusses using one ViewStub.