以编程方式在中间包含布局

时间:2015-08-24 00:00:10

标签: android android-layout android-fragments android-activity android-xml

如何以编程方式在另一个布局中的特定位置包含布局?

例如,如果我有这样的布局:

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

    <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <TextView
            android:id="@+id/some_text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Hello, world!"
            />

        // INCLUDE HERE

    </LinearLayout>

</LinearLayout>

如何在父布局中的特定位置包含以下布局(以编程方式)?

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="wrap_content">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <ImageView
            android:id="@+id/some_image"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            />

    </LinearLayout>

</LinearLayout>

1 个答案:

答案 0 :(得分:1)

将id添加到垂直方向的线性布局(例如:主视图)。以及动态视图的代码如下。

LinearLayout masterView = (LinearLayout)findViewById(R.id.masterView);

        LinearLayout childView = new LinearLayout(this);
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        childView.setLayoutParams(lp);

        LinearLayout childToChildView = new LinearLayout(this);
        childToChildView.setLayoutParams(lp);

        ImageView imageView = new ImageView(this);
        ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        imageView.setLayoutParams(layoutParams);
        imageView.setId(View.generateViewId());//some integer number

        childToChildView.addView(imageView);

        childView.addView(childToChildView);

        masterView.addView(childView);