如何多次向线性布局添加膨胀视图?

时间:2016-06-12 11:46:55

标签: android

我正在尝试在LinearLayout容器中添加一个膨胀的视图。但是我让孩子已经有了父母问题。 以下是我的容器多次的xml文件。 的 activity_main.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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin">

    <LinearLayout
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:background="@android:color/black"
        ></LinearLayout>
</LinearLayout>

item_button.xml 是我想要扩充到容器中的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="wrap_content"
    android:gravity="center_horizontal"
    android:background="@color/purple"
    android:orientation="vertical">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="25sp"
        android:text="Button 1"
        android:padding="20dp"
        android:background="@color/colorAccent"
        />

</LinearLayout>

以下是onCreate方法中的java代码。我想多次将childView添加到容器中。:

        View childView;
        LayoutInflater inflater = (LayoutInflater)   this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        childView = inflater.inflate(R.layout.item_button, null);
        container.addView(childView);
        container.addView(childView);

但是,在视图中多次添加子项会出现以下错误:

The specified child already has a parent. You must call removeView()
on the child's parent first.

2 个答案:

答案 0 :(得分:6)

发生这种情况是因为您要多次添加相同的视图,要实现您想要实现的目标,您只需添加一次视图,因此每次要将视图添加到视图时都必须创建新视图布局。

让我们假设您要添加两次:

View childView1, childView2;
LayoutInflater inflater = (LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
childView1 = inflater.inflate(R.layout.item_button, null);
childView2 = inflater.inflate(R.layout.item_button, null);
container.addView(childView1);
container.addView(childView2);

或者,如果您想要多次添加视图:

View v1, v2, v3;
View[] childViews = new View[]{v1,v2,v3};
LayoutInflater inflater = (LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
for(int v = 0; v < childViews.length; v++){
    childViews[v] = inflater.inflate(R.layout.item_button, null);
    container.addView(childViews[v]);
}

答案 1 :(得分:6)

由于已将膨胀视图添加到父布局,因此每次添加前都需要对其进行充气。你的代码应该是这样的:

View childView;
LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
for (int i = 0; i < count; i++) {
    childView = inflater.inflate(R.layout.item_button, null);
    container.addView(childView);
}

其中count显然是您要添加item_button布局的次数。

相关问题