Android中ListView子项margin失效解决办法

ListView是Android开发中的常用控件,在其子项布局文件中,如果在子项顶级布局中设置margin值,如下所示:

1
2
3
4
5
6
7
8
9
10
<LinearLayout  
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_marginTop="5dp"
android:layout_marginBottom="3dp"
android:background="@drawable/rect_gray" >

其中在四个方向都设置了margin值,但实际效果图如下:

从图中可以看出并没有实际产生margin值效果。
谷歌一下,在stackoverflow上找到了答案,要想让ListView中两个item之间产生margin间隙,只需在item布局最外层再加上一个LinearLayout布局,然后再第二层中设置margin属性才能生效,代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<LinearLayout  
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="100dp" >

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_marginTop="5dp"
android:layout_marginBottom="3dp"
android:background="@drawable/rect_gray" >

效果如下所示:

产生了预期的margin效果。