Get height for RecyclerView child views at runtime

╄→尐↘猪︶ㄣ 提交于 2019-12-04 19:02:45

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 coz they are not counted on measure totalHeight += 1; - is to cause adapter to bind next view holder ;)

in View Holder:

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);

You can override onLayoutChildren in the LayoutManager and measure it if state.isPreLayout return false. I'm hoping that you are not changing the total size of the View because LayoutManager will not see this change. Also because layout requests are disabled at that stage, your view will not get a new measure and layout.

If it resizes your view, do it in onBind and measure the textview yourself to decide whether you want to enable the button or not.

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