androidandroid-viewandroid-recyclerviewandroid-viewgroup

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.


Solution

  • 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.