Android开发:如何设置布局元素高度自适应至主视图底部无需硬编码
安卓布局高度适配解决方案
当前布局对应的效果如下:
问题说明
现有布局需要硬编码MapView控件高度才能正常显示,预期让MapView高度自动延伸至主视图底部,无法仅通过修改height属性实现,需要配合ScrollView的专属属性和父布局参数调整,具体修改步骤如下:
- 给外层
<ScrollView>节点添加android:fillViewport="true"属性,该属性会让ScrollView的内容区域允许撑满ScrollView本身的可视高度,解决ScrollView默认仅包裹内容高度的限制。 - 将ScrollView下的
<RelativeLayout>节点的android:layout_height属性从wrap_content修改为match_parent,让父布局可以占满ScrollView的全部可视高度。 - 修改
<org.osmdroid.views.MapView>节点属性:删除硬编码的200dp高度,改为android:layout_height="match_parent",同时添加android:layout_alignParentBottom="true"属性,让MapView顶部对齐上方LinearLayout的底部、底部对齐父布局底部,自动填充中间剩余空间。
修改后完整代码
<?xml version="1.0" encoding="utf-8"?> <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:fillViewport="true" xmlns:app="http://schemas.android.com/apk/res-auto" tools:context=".pkgFragment.LocationAddFragment"> <RelativeLayout android:layout_width="match_parent" android:layout_height="match_parent"> <LinearLayout android:id="@+id/llLayoutAddLocation" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@+id/abLayoutAddLocation" android:layout_marginLeft="30dp" android:layout_marginRight="30dp" android:orientation="vertical"> <GridLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:columnCount="2" android:rowCount="1" > <com.google.android.material.switchmaterial.SwitchMaterial android:layout_columnWeight="1" android:layout_height="match_parent" android:text="@string/vehicle_name"/> <com.google.android.material.switchmaterial.SwitchMaterial android:layout_columnWeight="1" android:layout_height="match_parent" android:text="@string/vehicle_name"/> </GridLayout> </LinearLayout> <org.osmdroid.views.MapView android:layout_width="match_parent" android:layout_height="match_parent" android:layout_below="@id/llLayoutAddLocation" android:layout_alignParentBottom="true" > </org.osmdroid.views.MapView> </RelativeLayout> </ScrollView>
注意事项
如果后续上方LinearLayout的内容增加,导致整体布局高度超过屏幕高度,ScrollView依然可以正常滚动,适配长内容场景。
内容的提问来源于stack exchange,提问作者Funny Moments
相关产品推荐
相关产品推荐

