Android布局异常:代码与XML均失效,add_warranty按钮消失
解决动态添加按钮后
add_warranty按钮消失的问题 嘿,我一眼就揪出问题所在了!你的根布局是垂直方向的LinearLayout,但里面的ScrollView设置了android:layout_height="match_parent"——这会让ScrollView把父布局的所有可用高度都占满,直接把下面的add_warranty按钮挤到屏幕外面去了,所以你才看不到它。
修复方案
只需要调整ScrollView的布局参数,让它占据除底部按钮外的剩余空间就行:
把ScrollView的android:layout_height从match_parent改成0dp,再加上android:layout_weight="1",这样ScrollView会自动填充按钮之外的所有空间,按钮就能稳稳地显示在底部了。
修改后的activity.xml代码如下:
<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"> <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="bottom" android:background="@drawable/mybutton" android:text="@string/add_button" android:scaleType="centerInside" android:layout_marginBottom="5dp"/> </LinearLayout>
原理说明
在垂直方向的LinearLayout中,layout_weight属性会让控件按比例分配剩余空间。给ScrollView设置layout_weight="1"并把高度设为0dp,它就会优先占据父布局中除了底部按钮(高度为wrap_content)之外的所有空间,这样按钮就不会被遮挡,动态添加的内容也能正常在ScrollView里滚动显示。
另外你动态添加按钮的代码是完全没问题的,不用做任何修改~
内容的提问来源于stack exchange,提问作者Jochem
相关产品推荐
相关产品推荐

