美文网首页
RecyclerView换行(自定义一个布局管理器)

RecyclerView换行(自定义一个布局管理器)

作者: 图之 | 来源:发表于2018-12-07 09:40 被阅读0次
    public class 初一LayoutManager extends RecyclerView.LayoutManager {
    
        @Override
        public RecyclerView.LayoutParams generateDefaultLayoutParams() {
            return new RecyclerView.LayoutParams(
                    RecyclerView.LayoutParams.WRAP_CONTENT,
                    RecyclerView.LayoutParams.WRAP_CONTENT);
        }
    
        @Override
        public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
            try {
                super.onLayoutChildren(recycler, state);
    
                //分离和废弃附加的视图
                detachAndScrapAttachedViews(recycler);
                //获取屏幕宽度
                int sumWidth = getWidth();
    
    
                //recyclerview行宽
                int curLineWidth = 0;
                //recyclerview行高
                int  curLineTop = 0;
                //最后一个item的最大可行高度
                int lastLineMaxHeight = 0;
                for (int i = 0; i < getItemCount(); i++) {
                    //获取第i 个位置的item的view
                    View view = recycler.getViewForPosition(i);
                    //添加这个item到recyclerview中
                    addView(view);
                    //获取添加了item后的recyclerview
                    measureChildWithMargins(view, 0, 0)
                   //获取添加了item后recyclerview的宽度;
                    int width = getDecoratedMeasuredWidth(view);
                  //获取添加了item后recyclerview的宽度;
                    int height = getDecoratedMeasuredHeight(view);
                  //recyclerview行宽+item.getWidth
                    curLineWidth += width;
                    if (curLineWidth <= sumWidth) {
                        //不需要换行
                        layoutDecorated(view, curLineWidth - width, curLineTop, curLineWidth, curLineTop + height);
                        //比较当前行多有item的最大高度
                        lastLineMaxHeight = Math.max(lastLineMaxHeight, height);
                    } else {
                        //换行
                        curLineWidth = width;
                        if (lastLineMaxHeight == 0) {
                            lastLineMaxHeight = height;
                        }
                        //记录当前行top
                        curLineTop += lastLineMaxHeight;
    
                        layoutDecorated(view, 0, curLineTop, width, curLineTop + height);
                        lastLineMaxHeight = height;
                    }
                }
            } catch (IndexOutOfBoundsException e) {
                
            }
    
        }
    
    }
    

    相关文章

      网友评论

          本文标题:RecyclerView换行(自定义一个布局管理器)

          本文链接:https://www.haomeiwen.com/subject/pebzcqtx.html