Get height for RecyclerView child views at runtime

后端 未结 2 2048
闹比i
闹比i 2021-01-06 13:57

I\'m trying to make an expandable TextView that expands/collapses when a user presses a button. The TextView and ImageButton are in a CardView, which is added to a RecyclerV

2条回答
  •  暖寄归人
    2021-01-06 14:35

    LinearLayout.LayoutParams - this could be RelativeLayout.LayoutParams according to yours main layout

    mParentContainer - this is RecyclerView - passed to yours adapter

    Utils.dpToPx(8+15); - here addition of margins cause they are not counted on measure

    totalHeight += 1; - is to cause adapter to bind next view holder

    in ViewHolder:

    int totalHeight = 0;
    for (int i = 0; i < getItemCount(); i++){
    
        View chView = viewHolder . itemView;
        chView.measure(
            View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
            View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
        );
    
        totalHeight += chView.getMeasuredHeight();
        totalHeight += Utils.dpToPx(8 + 15);
    }
    
    totalHeight += 1;
    LinearLayout.LayoutParams listParams = (LinearLayout.LayoutParams) mParentContainer . getLayoutParams ();
    listParams.height = totalHeight;
    mParentContainer.setLayoutParams(listParams);
    
    

提交回复
热议问题