如何在"onBindViewHolder"中获取recyclerview项目的高度 [英] How to get the height of recyclerview item in "onBindViewHolder"

查看:1416
本文介绍了如何在"onBindViewHolder"中获取recyclerview项目的高度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

RecyclerView项的高度未固定,我需要为每个项设置背景图像,所以我想获取recyclerview项的高度以调整图像大小,但是itemView.getHeight()总是在onBindViewHolder中返回0.

The height of RecyclerView item is not fixed,i need to set the background image for every item,so I want to get the height of recyclerview's item to resize the Image,but the itemView.getHeight() always return 0 in onBindViewHolder.

我尝试搜索许多问题或文章,但仍然无法获得很好的解决方案.

I have try to search many questions or articles,but i still cant get a good soluation.

推荐答案

手动测量视图

view.measure(
             View.MeasureSpec.makeMeasureSpec(recyclerViewWidth, View.MeasureSpec.EXACTLY),
             View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));

并使用view.getMeasuredHeight()

背景

仅在测量后,视图才会为View.getHeight()返回有效值.当视图即将显示在屏幕上时,测量本身将由系统自动进行.

A view will return a valid value for View.getHeight()only after it has been measured. The measuring itself will automatically happen by the system when the view is about to be displayed on screen.

当Android要显示布局时,它将为视图树中的每个视图递归调用view.layout()函数.每个父母都告诉他们的孩子他们可能有的限制(宽度/高度),并要求他们自己view.measure().结果,该视图将根据约束中的测量值 BASED 存储在指定成员中(MeasuredHeight/Width).请注意,此时view.getMeasuredHeight()将保留该值,而view.getHeight()仍然无效. view.getHeight()仅在视图在UI层次结构中具有实际高度时才返回有效值.

When Android wants to display the layout, it will recursively call the view.layout() function for each view in the view tree. Each Parent tells its children the constraints they might have (width/height) and ask them to view.measure() themselves. As a result, the view will store the measured values BASED on the constraints in designated members (MeasuredHeight/Width). Note that at this point view.getMeasuredHeight() will hold the value while view.getHeight() will still be invalid. view.getHeight() will only return a valid value once the view has an actual height in the UI hierarchy.

回顾

因此,要知道视图元素的高度,在系统对其进行测量和布局之前,我们需要手动调用view.measure()函数.

So, to know the height of a view element, before it has been measured and laid out by the system, we will need to invoke the view.measure() function manually.

measure函数期望从视图LayoutParams +父约束中派生出2个参数.

The measure function expects 2 parameters which derived from the view LayoutParams + the parent constraints.

在上面的代码示例中,我们正在测量强制其宽度为完全父级(RecycleView)宽度且高度不受限制的视图.

In the above code sample, we are measuring the view forcing its width to be EXACTLY the width of the parent (the RecycleView), and the height is not limited.

这篇关于如何在"onBindViewHolder"中获取recyclerview项目的高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆