Measure Recyclerview before it appears

前提是你 提交于 2019-12-10 03:52:29

问题


I am currently experiencing an issue when measuring a recyclerView before it appears. I need the measuredHeight in order to start an "expand" animation.

This was previously done for a gridView in the code I'm working on and I am trying to migrate it to a RecyclerView with GridLayoutManager

final int widthSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
final int heightSpec = View.MeasureSpec.makeMeasureSpec(MEASURED_SIZE_MASK, View.MeasureSpec.AT_MOST);
mGridView.measure(widthSpec, heightSpec);
int targetHeight = mGridView.getMeasuredHeight();

It was working with the gridView but if I call measure method with same measure specs on the recyclerView, result is always 16777215 which I think might be a max value for something but I cannot say what.

I saw some post explaining that a view can be measured before it is rendered on screen by measuring it with following measure specs :

final int widthSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
final int heightSpec = View.MeasureSpec.makeMeasureSpec(0,View.MeasureSpec.UNSPECIFIED);

but I get 0 for recyclerView.getMeasuredHeight();.

Is there a way to properly measure the height of the recyclerView before it is rendered on screen ?

Thanks.


回答1:


Are you trying to measure the view before adding it? If so, that is dangerous.

Also, in terms of RecyclerView, unfortunately, existing layout managers don't yet support WRAP_CONTENT. They rely on the base implementation which supports match_paren & exact dimensions.

If you know your item's height, you can extend GridLayoutManager, override onMeasure and measure it there yourself.




回答2:


Thanks to yigit post, I could finally calculate future recyclerView height by manually inflating a child's view, measuring it with :

final int widthSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
final int heightSpec = View.MeasureSpec.makeMeasureSpec(MEASURED_SIZE_MASK, View.MeasureSpec.AT_MOST);

And finally multiplying its measuredHeight by the number of lines contained in the gridLayoutManager. Hope WRAP_CONTENT support will come soon for RecycleViews layoutManagers.




回答3:


See also How do I make WRAP_CONTENT work on a RecyclerView.

If you place your RecyclerView inside a container such as RelativeLayout or NestedScrollView, you can obtain it's measures with recyclerView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED) or other variants you like. Before measuring it would be better to call post { /* measure here */ }.



来源:https://stackoverflow.com/questions/26517930/measure-recyclerview-before-it-appears

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!