Android布局中Google Map容器无法设置底部边距求助
你遇到的底部margin不生效的问题,核心原因在于RelativeLayout的高度设置为match_parent,而它的父容器是一个高度由layout_weight分配的LinearLayout(高度为0dp)。当RelativeLayout使用match_parent时,它会试图占满父容器的全部可用高度,这时候底部的margin会被父容器的边界“挤压”,导致无法显示——因为父容器的高度是固定的,RelativeLayout加上底部margin后总高度会超过父容器,超出部分就被裁剪掉了。
另外,内部的MapFragment设置了match_parent的高度,也会让RelativeLayout的高度被Fragment完全撑满,进一步掩盖了底部margin的空间。
这里提供两种可行的修复方案,你可以根据需求选择:
方案一:调整RelativeLayout的布局参数
把RelativeLayout的android:layout_height从match_parent改为0dp,同时添加android:layout_weight="1",让它在父LinearLayout中填充剩余空间,这样margin就能正常生效了:
<RelativeLayout android:id="@+id/rl_layout" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:layout_margin="10dp" android:background="@drawable/shadow" android:orientation="vertical"> <fragment android:id="@+id/map" android:name="com.google.android.gms.maps.SupportMapFragment" android:layout_width="match_parent" android:layout_height="match_parent" /> </RelativeLayout>
这样修改后,RelativeLayout会根据weight分配到父容器的剩余高度,同时保留所有方向的margin,底部的空间就不会被挤压了。
方案二:给父容器添加padding代替margin
如果不想修改RelativeLayout的高度设置,可以给它的父容器(id为gview2的LinearLayout)添加android:padding="10dp",然后移除RelativeLayout的android:layout_margin="10dp"。这样整个底部区域都会有内边距,MapFragment也会被限制在padding范围内,视觉效果和设置margin是一样的:
<LinearLayout android:id="@+id/gview2" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:orientation="vertical" android:padding="10dp"> <TextView android:id="@+id/headertext" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="#1d925c" android:gravity="center" android:padding="10dp" android:textColor="#ffffff" /> <RelativeLayout android:id="@+id/rl_layout" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/shadow" android:orientation="vertical"> <fragment android:id="@+id/map" android:name="com.google.android.gms.maps.SupportMapFragment" android:layout_width="match_parent" android:layout_height="match_parent" /> </RelativeLayout> </LinearLayout>
这种方法更简洁,适合希望整个底部区域统一内边距的场景。
另外注意,你的RelativeLayout里的android:layout_below="@+id/headertext"是无效的,因为layout_below是RelativeLayout的子控件才会用到的属性,RelativeLayout作为LinearLayout的子控件,这个属性不会起作用,建议删除它,避免冗余代码。
内容的提问来源于stack exchange,提问作者MARSH

