Android中RecycleView使用GridLayoutManager时自适应高度

论坛 期权论坛 编程之家     
选择匿名的用户   2021-6-2 16:08   759   0

使用下面的代码,默认一行3个child


recyclerView.setLayoutManager(new GridLayoutManager(activity, 3) {
                @Override
                public void onMeasure(RecyclerView.Recycler recycler, RecyclerView.State state, int widthSpec, int heightSpec) {
                    super.onMeasure(recycler, state, widthSpec, heightSpec);
                    int measuredWidth = recyclerView.getMeasuredWidth();
                    int measuredHeight = recyclerView.getMeasuredHeight();
                    int myMeasureHeight = 0;
                    int count = state.getItemCount();
                    for (int i = 0; i < count; i++) {
                        View view = recycler.getViewForPosition(i);
                        if (view != null) {
                            if (myMeasureHeight < measuredHeight && i % 3 == 0) {
                                RecyclerView.LayoutParams p = (RecyclerView.LayoutParams) view.getLayoutParams();
                                int childWidthSpec = ViewGroup.getChildMeasureSpec(widthSpec,
                                        getPaddingLeft() + getPaddingRight(), p.width);
                                int childHeightSpec = ViewGroup.getChildMeasureSpec(heightSpec,
                                        getPaddingTop() + getPaddingBottom(), p.height);
                                view.measure(childWidthSpec, childHeightSpec);
                                myMeasureHeight += view.getMeasuredHeight() + p.bottomMargin + p.topMargin;
                            }
                            recycler.recycleView(view);
                        }
                    }
//                    Log.i("Height", "" + Math.min(measuredHeight, myMeasureHeight));
                    setMeasuredDimension(measuredWidth, Math.min(measuredHeight, myMeasureHeight));
                }


分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP