动态添加Item的ScrollView下方固定Button不显示问题
我来帮你搞定这个Button消失的问题!你的布局里Button看不到,核心原因是ScrollView的高度设置和fillViewport属性的组合把Button的空间挤没了。
问题根源
你给外层LinearLayout设置了match_parent的高度,并且是垂直方向排列。而ScrollView的layout_height="wrap_content"加上fillViewport="true",会让ScrollView尽可能占据父容器的所有可用高度——相当于把整个屏幕高度都占了,Button自然被推到屏幕外面,根本看不到。
两种可行的解决方案
方案1:用LinearLayout权重分配空间(推荐)
给ScrollView设置layout_weight="1",同时把layout_height改成0dp。这样ScrollView会自动占据除了Button之外的所有剩余高度,Button就能稳稳固定在底部。
修改后的完整布局代码:
<LinearLayout android:id="@+id/list_warrantys" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <ScrollView android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:fillViewport="true"> <LinearLayout android:id="@+id/show_warratys" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="wrap_content"> </LinearLayout> </ScrollView> <Button android:id="@+id/add_warranty" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:background="@drawable/mybutton" android:text="@string/add_button" android:layout_marginBottom="5dp"/> </LinearLayout>
方案2:改用RelativeLayout定位
如果更习惯用相对布局,可以把外层容器换成RelativeLayout,通过layout_above和layout_alignParentBottom属性来固定两个控件的位置:
<RelativeLayout android:id="@+id/list_warrantys" android:layout_width="match_parent" android:layout_height="match_parent"> <ScrollView android:layout_width="match_parent" android:layout_height="match_parent" android:layout_above="@id/add_warranty" android:fillViewport="true"> <LinearLayout android:id="@+id/show_warratys" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="wrap_content"> </LinearLayout> </ScrollView> <Button android:id="@+id/add_warranty" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:background="@drawable/mybutton" android:text="@string/add_button" android:layout_marginBottom="5dp"/> </RelativeLayout>
小提示
方案1的LinearLayout权重方式更适合这种垂直方向的空间分配,逻辑更直观,后续如果要添加其他顶部/中间控件,扩展性也更强。
内容的提问来源于stack exchange,提问作者Jochem
相关产品推荐
相关产品推荐

