首页 > 解决方案 > 如何将 ImageView 高度与其父级 wrap_content 匹配?(回收站查看项目)

问题描述

我有一个RecyclerView带有LinearLayout. 的LinearLayout高度设置为wrap_content。在里面LinearLayout,我想要一个ImageView与高度相匹配的三角形,LinearLayout得到这样的东西:

在此处输入图像描述

使用固定高度LinearLayout,我可以在 XML 中设置它:

 <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:scaleType="fitXY"
        android:adjustViewBounds="true"/>

为了使用可变高度获得相同的结果,我尝试将ImageView高度和宽度设置为 0,然后在内部以编程方式调整它们onBindViewHolder

holder.mLinearLayout.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
int layoutHeight = holder.mLinearLayout.getMeasuredHeight();

holder.mImageView.getLayoutParams().height = layoutHeight;
holder.mImageView.getLayoutParams().width = layoutHeight;

holder.mImageView.requestLayout();

它看起来像调整了ImageView作品的大小,但它没有显示图像。我在这里做错了什么?

标签: androidandroid-recyclerviewimageview

解决方案


我的错误是我不小心从我的 XML 中删除了图像源。上面的代码现在显示了一个图像,但它仍然不能正常工作。

要获得正确的高度,您必须替换测量参数:

holder.mLinearLayout.measure(
                View.MeasureSpec.makeMeasureSpec(Resources.getSystem().getDisplayMetrics().widthPixels, View.MeasureSpec.EXACTLY),
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
        );

我不确定这是否是最好的解决方案,但它确实有效。


推荐阅读