Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Measure Recyclerview before it appears

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.

like image 625
Loïc Avatar asked Oct 22 '14 22:10

Loïc


People also ask

How do I find the size of a recycler view?

getItemCount() : RecyclerView calls this method to get the size of the data set. For example, in an address book app, this might be the total number of addresses. RecyclerView uses this to determine when there are no more items that can be displayed.

What is LayoutManager in RecyclerView?

A LayoutManager is responsible for measuring and positioning item views within a RecyclerView as well as determining the policy for when to recycle item views that are no longer visible to the user.

How does recycler view work internally?

RecyclerView will go to Adapter and request it to create new ViewHolder from the ViewType . Adapter will create a new ViewHolder and bind it with the data for the requested position . Adapter will return ViewHolder to RecyclerView and RecyclerView return the View back to LayoutManger .

Is RecyclerView deprecated?

Today, suddenly Recyclerview. Viewholder became deprecated. Other, android project is no deprecated.


1 Answers

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.

like image 154
Loïc Avatar answered Sep 27 '22 15:09

Loïc