如何在其他布局中充气视图?

时间:2016-03-07 09:12:07

标签: android horizontal-scrolling layout-inflater

enter image description here

我必须创建一个包含框的horizental滚动视图。每个盒子最多只能包含三个项目。所以我的逻辑是:

  1. 在Horizental ScrollView中创建框列表

    ...\\myproject\\:\\HomePage.html
  2. 创建box.xml

    <HorizontalScrollView
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
         android:fillViewport="true">
         <LinearLayout
              android:id="@+id/ll_list"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:orientation="horizontal">
         </LinearLayout>
    </HorizontalScrollView>
    
  3. 为项目创建item.xml(在框中)

  4. 在Java中 例如,有7项,所以我需要3个盒子。 这是我的代码,

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

    问题是我得到了错误 ll_list.addView(ll_box); java.lang.IllegalStateException:指定的子级已有父级。您必须首先在孩子的父母上调用removeView()。

    如果你不明白这个问题,请问我。我真的需要你的帮助。谢谢。

1 个答案:

答案 0 :(得分:2)

您必须在每一步创建一个新的box View

这样的事情:

for (int i=0; i<idx; i++ ){

   View box = getLayoutInflater().inflate(R.layout.box, null);
   LinearLayout ll_box = (LinearLayout)box.findViewById(R.id.ll_box);

   for(int j=0; j<3; j++){
       ll_box.addView(LayoutInflater.from(this).inflate(R.layout.item, null));
   }
   ll_list.addView(box); //here add `box` instead of `ll_box`!!
}