LinearLayout动态添加多个View异常问题求助
问题分析与解决方案
我一眼就发现了问题的核心——你动态添加的两个View的根布局高度都设置成了match_parent,这会导致第一个View直接占据ScrollView的全部可用高度,第二个View虽然被成功添加,但被挤到了屏幕可见范围之外,看起来像是“失效”了。
具体原因
你的sensor_item和nosensor_item布局的根ConstraintLayout都配置了:
android:layout_height="match_parent"
而它们的父容器box_Parent是垂直方向的LinearLayout,外层套着ScrollView。当第一个View被添加后,它会撑满整个ScrollView的高度,第二个View被追加到它下方后,自然就超出了屏幕显示区域,所以你看不到它。
解决方案
把两个动态添加布局的根ConstraintLayout高度从match_parent改为wrap_content,让它们根据内部内容自适应高度:
修改sensor_item.xml和nosensor_item.xml的根布局:
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:fillViewport="true" android:id="@+id/constraintLayout" android:layout_width="match_parent" android:layout_height="wrap_content" <!-- 这里改成wrap_content --> app:layout_constraintEnd_toEndOf="parent" app:layout_constraintTop_toTopOf="parent">
额外优化建议
- 使用Fragment提供的LayoutInflater:在
onCreateView中,建议用方法参数里的inflater加载布局,而不是layoutInflater,这样能继承Fragment的主题配置:val view = inflater.inflate(R.layout.sensor_item, container, false) val view2 = inflater.inflate(R.layout.nosensor_item, container, false) - 简化添加View的代码:如果只是想把两个View依次添加到按钮后面,不需要指定索引,直接调用
addView()即可,默认会添加到LinearLayout末尾:
效果和你指定索引2、3完全一致,但代码更简洁易读。insertPoint.addView(view) insertPoint.addView(view2)
验证效果
修改后,两个View会根据自身内容高度依次排列在按钮下方,ScrollView也能正常滚动显示所有内容,和你单独添加时的正常效果一致。
内容的提问来源于stack exchange,提问作者Nicolas Fournier
相关产品推荐
相关产品推荐

