![](/img/trans.png)
[英]How can I get wrap_content or match_parent layout width and height in android?
[英]How can I match an ImageView height to its parent that is wrap_content? (RecyclerView Item)
我有一个带有LinearLayout
的RecyclerView
项目。 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
的大小调整有效,但它不显示图像。 我在这里做错了什么?
我的错误是我不小心从我的 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.