如何在XML中设置HorizontalScrollView内ImageView适配父布局高度
问题解决方法
问题根源
布局的核心问题出在内层LinearLayout的高度配置上:
- 你给
ImageView设置了android:layout_height="match_parent",但它的直接父布局LinearLayout的高度是wrap_content,子控件的match_parent需要父布局有明确的固定高度/匹配父高度才能生效,所以你的高度配置一直不生效。 - 额外说明:
adjustViewBounds="true"和centerCrop同时使用的时候,会优先按图片宽高比缩放,也可能干扰高度匹配的效果,如果不需要严格保留图片比例可以去掉这个属性。
修改后的XML代码
<HorizontalScrollView android:layout_width="fill_parent" android:orientation="horizontal" android:layout_height="@dimen/scrollShareImgHeight"> <!-- 把LinearLayout的高度改成match_parent,和HorizontalScrollView高度对齐 --> <LinearLayout android:layout_width="wrap_content" android:layout_height="match_parent" android:id="@+id/sharedLinearLayoutImgs" android:orientation="horizontal"> <ImageView android:layout_width="wrap_content" android:layout_height="match_parent" android:scaleType="centerCrop" <!-- 如果不需要严格保留图片原始宽高比,可以删掉adjustViewBounds配置 --> <!-- android:adjustViewBounds="true" --> android:src="@drawable/loremipsum"/> </LinearLayout> </HorizontalScrollView>
动态添加图片注意事项
如果你后续是通过代码动态往LinearLayout里加图片,创建ImageView的时候要给它设置高度为MATCH_PARENT的布局参数:
// Java示例 ImageView newImg = new ImageView(context); LinearLayout.LayoutParams params = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.MATCH_PARENT ); newImg.setLayoutParams(params); newImg.setScaleType(ImageView.ScaleType.CENTER_CROP); sharedLinearLayoutImgs.addView(newImg);
内容的提问来源于stack exchange,提问作者Kaki In
相关产品推荐
相关产品推荐

