Sachin Soma
Sachin Soma

Reputation: 3802

Set RecyclerView's height based on its item's height

Is there any way to set height of Recyclerview based on its item's height . Like (item's height * count of items which can be set to any number) should be the height of the RecyclerView when it loads.

I am able to set its height on item click. //This is my interface

@Override
    public void onSubCategoryClicked(View view, int position) {

            reyclerview.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, view.getHeight()*2));


}

Now I want to set height of recyclerview when it loads.

Upvotes: 0

Views: 579

Answers (1)

Pawel
Pawel

Reputation: 17248

You can inflate and measure your ViewHolder without actually laying it out, this will let you take its size and put it on top of RecyclerView.

Note that for this to work properly you must ensure your ViewHolder size is not affected by binding data (no resizable images, only textviews with fixed line count etc.) and you only have a single item view type (or at least equal height on all of them).

Inside your activity/fragment after initializing your RecyclerView:

// create viewholder using adapter - if you have custom view type use it instead of 0
RecyclerView.ViewHolder vh = recyclerView.getAdapter().createViewHolder(recyclerView, 0);
// measure item view using recycler views layout manager
recyclerView.getLayoutManager().measureChildWithMargins(vh.itemView, 0, 0);
// now carry over viewholder size onto recyclerView, for example show 5 items
recyclerView.getLayoutParams().height = vh.itemView.getMeasuredHeight() * 5;
// finally throw created viewholder into scrap pool so it can be reused
recyclerView.getRecycledViewPool().putRecycledView(vh);

Upvotes: 3

Related Questions