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

查看:142
本文介绍了如何在“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()函数.每个 Parent 告诉它的孩子他们可能有的约束(宽度/高度),并要求他们自己view.measure().因此,视图将根据指定成员(MeasuredHeight/Width)的约束存储BASED测量值.请注意,此时 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 函数需要 2 个从视图 LayoutParams + 父约束派生的参数.

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天全站免登陆