我试图将动态创建的几个RelativeLayouts添加到LinearLayout中,该LinearLayout位于RelativeLayout内部,位于ScrollView内部.当所有视图的总高度超过手机屏幕的大小时,所有视图都会正确显示.但是,当动态添加的视图的总大小不足以填充屏幕时,仅显示第一个RelativeLayout元素,而其他元素不显示在屏幕中.我真的很无望,也不明白为什么.
以下是在线性布局中动态填充视图的代码:
- LinearLayout commentsLayout = (LinearLayout) findViewById(R.id.comments_layout);
- LayoutInflater inflater = (LayoutInflater)
- this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
- for(Comment c: commentsList) {
- RelativeLayout layoutItem = (RelativeLayout) inflater.inflate(
- R.layout.list_item_comment,null,false);
- TextView tv = (TextView) layoutItem.findViewById(R.id.textView);
- ImageView iv = (ImageView) layoutItem.findViewById(R.id.imageView);
- // set tv's text
- // set iv's image and onclicklistener,nothing fancy here,everything goes well
- commentsLayout.addView(layoutItem);
- }
这是list_item_comment.xml:
- <RelativeLayout
- android:orientation="vertical"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:background="@color/white"
- >
- <ImageView
- android:id="@+id/imageView"
- android:layout_width="50dip"
- android:layout_height="50dip"
- android:layout_alignParentLeft="true"
- android:layout_marginTop="10dp"
- android:layout_marginLeft="10dp"
- />
- <TextView
- android:id="@+id/textView"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:layout_margin="10dp"
- android:textSize="16sp"
- android:layout_toRightOf="@id/imageView"
- />
- </RelativeLayout>
这是此活动的xml文件:
- <RelativeLayout
- android:orientation="vertical"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:id="@+id/main_layout"
- >
- ...
- <ScrollView
- android:orientation="vertical"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:fillViewport="true"
- android:id="@+id/scrollView"
- >
- <RelativeLayout
- android:orientation="vertical"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:id="@+id/relativeContainer"
- >
- ...
- <LinearLayout
- android:orientation="vertical"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:id="@+id/comments_layout"
- />
- </RelativeLayout>
- </ScrollView>
- </RelativeLayout>
截图:
有足够的布局:(正确一个,屏幕填充)
解决方法
而不是fill_parent,尝试更改< RelativeLayout>的layout_height.你的list_item_comment.xml到wrap_content.
另外,为什么还需要另一个< RelativeLayout>在你的< ScrollView>里面您的活动的xml. LinearLayout足以完成您希望活动的样子.也许你可以删除它.