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

nba*_*lle 35 layout android include android-layout

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

我想可以设置哪些content_layout应该动态地在运行时包括在内,所以我不想设定一个"layout="@+layout/content_layout"在我的XML文件.

这是我的布局:

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

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

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

我怎样才能做到这一点?

谢谢!

Mat*_*adt 39

<RelativeLayout android:id="@+id/rl" ...
Run Code Online (Sandbox Code Playgroud)

在你的代码中:

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

  • 我认为方法输入的顺序现在颠倒了:https://developer.android.com/reference/android/view/ViewGroup.html#addView(android.view.View, int) 所以它应该是```rl .addView(layoutInflater.inflate(R.layout.content_layout, this, false), 1 );``` (2认同)

Bry*_*nny 5

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

这个答案讨论了使用一个ViewStub.