繁体   English   中英

如何将 ImageView 高度与其父级 wrap_content 匹配? (RecyclerView Item)

[英]How can I match an ImageView height to its parent that is wrap_content? (RecyclerView Item)

我有一个带有LinearLayoutRecyclerView项目。 LinearLayout的高度设置为wrap_content 在那个LinearLayout ,我想要一个三角形的ImageViewLinearLayout的高度相匹配,以获得这样的东西:

在此处输入图片说明

使用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的大小调整有效,但它不显示图像。 我在这里做错了什么?

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM