RecyclerView流式布局

最近在做需求的时候,碰到有各种筛选项的界面,类似这样

 

这种筛选界面也比较常见,一般我们都采用RecyclerView来实现,当筛选项比较少的时候,我们选择使用线性布局来实现,当筛选项比较多,但是每个筛选项长度一样时,我们可以采用网格布局。但是这次的需求,筛选项有长有短,并且当每一行还有空间时,不能进行换行,因此RecyclerView自带的瀑布流布局也不能满足需求。

我们知道RecyclerView的布局是由LayoutManager负责,因此如果要实现这种效果,我把它称之为流式布局,需要自定义LayoutManager。首先我们来看一下LayoutManager的几个重要的方法

方法名作用
isAutoMeasureEnabled这个方法表示是否采用自动测量,一般都是true,否则就需要自己重写onMeasure方法。
generateDefaultLayoutParams这是个抽象方法,用于给ItemView设置布局参数,必须实现。

onMeasure

测量RecyclerView大小
onLayoutChildren对ItemView进行布局,Item如何摆放,全看这个方法如何实现

那么我们要重写LayoutManager就简单需要以下几个步骤

重写isAutoMeasureEnabled

   override fun isAutoMeasureEnabled(): Boolean {
        return true
    }

只需要返回true,代表RecyclerView自动测量。RecyclerView的三个默认实现的布局管理器也是返回true的。

重写generateDefaultLayoutParams

 override fun generateDefaultLayoutParams(): RecyclerView.LayoutParams {
        return RecyclerView.LayoutParams(
            RecyclerView.LayoutParams.WRAP_CONTENT,
            RecyclerView.LayoutParams.WRAP_CONTENT
        )
    }

没有什么特殊要求,直接返回自适应即可,给Item设置默认的布局参数。这个方式必须实现。

重写onLayoutChildren

由于isAutoMeasureEnabled直接返回true,因此没有必要重写onMeasure方法,启动自动测量。但我们需要重点实现onLayoutChildren方法,这是我们自定义LayoutManager的核心所在。

  override fun onLayoutChildren(recycler: RecyclerView.Recycler, state: RecyclerView.State?) {
        //这里是在布局前将所有在显示的HoldView从RecyclerView中剥离,将其放在缓存中,方便重新布局时使用。
        detachAndScrapAttachedViews(recycler)
        var curLineWidth = 0 //curLineWidth 累加item布局时的x轴偏移
        var curLineTop = 0 //curLineTop 累加item布局时的y轴偏移
        var lastLineMaxHeight = 0
        for (i in 0 until itemCount) {
            val view: View = recycler.getViewForPosition(i)
            //获取每个item的布局参数,计算每个item的占用位置时需要加上margin
            val params = view.layoutParams as RecyclerView.LayoutParams
            addView(view)
            measureChildWithMargins(view, 0, 0)
            val width = getDecoratedMeasuredWidth(view) + params.leftMargin + params.rightMargin
            val height = getDecoratedMeasuredHeight(view) + params.topMargin + params.bottomMargin
            curLineWidth += width //累加当前行已有item的宽度
            if (curLineWidth <= getWidth()) { //如果累加的宽度小于等于RecyclerView的宽度,不需要换行
                layoutDecorated(
                    view,
                    curLineWidth - width + params.leftMargin,
                    curLineTop + params.topMargin,
                    curLineWidth - params.rightMargin,
                    curLineTop + height - params.bottomMargin
                ) //布局item的真实位置
                //比较当前行多有item的最大高度,用于换行后计算item在y轴上的偏移量
                lastLineMaxHeight = Math.max(lastLineMaxHeight, height)
            } else { //换行
                curLineWidth = width
                if (lastLineMaxHeight == 0) {
                    lastLineMaxHeight = height
                }
                //记录当前行top
                curLineTop += lastLineMaxHeight
                layoutDecorated(
                    view,
                    params.leftMargin,
                    curLineTop + params.topMargin,
                    width - params.rightMargin,
                    curLineTop + height - params.bottomMargin
                )
                lastLineMaxHeight = height
            }
        }
    }

经过这三步就可以完整的实现一个自定义的LayoutManager。

下面是我自定义的流式布局完整代码

class FlowLayoutManager : RecyclerView.LayoutManager() {


    override fun isAutoMeasureEnabled(): Boolean {
        return true
    }

    override fun generateDefaultLayoutParams(): RecyclerView.LayoutParams {
        return RecyclerView.LayoutParams(
            RecyclerView.LayoutParams.WRAP_CONTENT,
            RecyclerView.LayoutParams.WRAP_CONTENT
        )
    }

    override fun onLayoutChildren(recycler: RecyclerView.Recycler, state: RecyclerView.State?) {
        //这里是在布局前将所有在显示的HoldView从RecyclerView中剥离,将其放在缓存中,方便重新布局时使用。
        detachAndScrapAttachedViews(recycler)
        var curLineWidth = 0 //curLineWidth 累加item布局时的x轴偏移
        var curLineTop = 0 //curLineTop 累加item布局时的y轴偏移
        var lastLineMaxHeight = 0
        for (i in 0 until itemCount) {
            val view: View = recycler.getViewForPosition(i)
            //获取每个item的布局参数,计算每个item的占用位置时需要加上margin
            val params = view.layoutParams as RecyclerView.LayoutParams
            addView(view)
            measureChildWithMargins(view, 0, 0)
            val width = getDecoratedMeasuredWidth(view) + params.leftMargin + params.rightMargin
            val height = getDecoratedMeasuredHeight(view) + params.topMargin + params.bottomMargin
            curLineWidth += width //累加当前行已有item的宽度
            if (curLineWidth <= getWidth()) { //如果累加的宽度小于等于RecyclerView的宽度,不需要换行
                layoutDecorated(
                    view,
                    curLineWidth - width + params.leftMargin,
                    curLineTop + params.topMargin,
                    curLineWidth - params.rightMargin,
                    curLineTop + height - params.bottomMargin
                ) //布局item的真实位置
                //比较当前行多有item的最大高度,用于换行后计算item在y轴上的偏移量
                lastLineMaxHeight = Math.max(lastLineMaxHeight, height)
            } else { //换行
                curLineWidth = width
                if (lastLineMaxHeight == 0) {
                    lastLineMaxHeight = height
                }
                //记录当前行top
                curLineTop += lastLineMaxHeight
                layoutDecorated(
                    view,
                    params.leftMargin,
                    curLineTop + params.topMargin,
                    width - params.rightMargin,
                    curLineTop + height - params.bottomMargin
                )
                lastLineMaxHeight = height
            }
        }
    }
}

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
RecyclerView本身并不支持流式布局,但是可以通过自定义LayoutManager来实现流式布局。下面是一个简单的实现步骤: 1. 创建一个继承自RecyclerView.LayoutManager的自定义LayoutManager。 2. 在自定义LayoutManager中重写onLayoutChildren方法,实现流式布局的摆放。 3. 在onMeasure方法中计算RecyclerView的宽高。 4. 在RecyclerView.Adapter中根据需要调整item的宽高,以适配流式布局。 以下是一个简单的示例代码: ```java public class FlowLayoutManager extends RecyclerView.LayoutManager { private int mTotalHeight; @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) { if (state.getItemCount() == 0) { return; } detachAndScrapAttachedViews(recycler); int offsetX = getPaddingLeft(); int offsetY = getPaddingTop(); int lineMaxHeight = 0; int width = getWidth(); for (int i = 0; i < getItemCount(); i++) { View child = recycler.getViewForPosition(i); addView(child); measureChildWithMargins(child, 0, 0); int childWidth = getDecoratedMeasuredWidth(child); int childHeight = getDecoratedMeasuredHeight(child); if (offsetX + childWidth > width - getPaddingRight()) { offsetX = getPaddingLeft(); offsetY += lineMaxHeight; lineMaxHeight = 0; } layoutDecorated(child, offsetX, offsetY, offsetX + childWidth, offsetY + childHeight); offsetX += childWidth; lineMaxHeight = Math.max(lineMaxHeight, childHeight); } mTotalHeight = offsetY + lineMaxHeight + getPaddingBottom(); } @Override public boolean canScrollVertically() { return true; } @Override public int scrollVerticallyBy(int dy, RecyclerView.Recycler recycler, RecyclerView.State state) { if (getChildCount() == 0 || dy == 0) { return 0; } int scrolled = 0; if (dy > 0) { View lastChild = getChildAt(getChildCount() - 1); int lastVisiblePos = getPosition(lastChild); if (lastVisiblePos == getItemCount() - 1 && lastChild.getBottom() - dy < getHeight() - getPaddingBottom()) { dy = lastChild.getBottom() - getHeight() + getPaddingBottom(); } } else { View firstChild = getChildAt(0); int firstVisiblePos = getPosition(firstChild); if (firstVisiblePos == 0 && firstChild.getTop() - dy > getPaddingTop()) { dy = firstChild.getTop() - getPaddingTop(); } } offsetChildrenVertical(-dy); scrolled += dy; fill(recycler); return scrolled; } private void fill(RecyclerView.Recycler recycler) { int topOffset = getPaddingTop(); int leftOffset = getPaddingLeft(); int lineMaxHeight = 0; int width = getWidth(); for (int i = 0; i < getChildCount(); i++) { View child = getChildAt(i); int childWidth = getDecoratedMeasuredWidth(child); int childHeight = getDecoratedMeasuredHeight(child); if (leftOffset + childWidth > width - getPaddingRight()) { leftOffset = getPaddingLeft(); topOffset += lineMaxHeight; lineMaxHeight = 0; } layoutDecorated(child, leftOffset, topOffset, leftOffset + childWidth, topOffset + childHeight); leftOffset += childWidth; lineMaxHeight = Math.max(lineMaxHeight, childHeight); } detachAndScrapAttachedViews(recycler); } @Override public int computeVerticalScrollOffset(RecyclerView.State state) { return computeVerticalScrollExtent(state); } @Override public int computeVerticalScrollExtent(RecyclerView.State state) { return getHeight() - getPaddingTop() - getPaddingBottom(); } @Override public int computeVerticalScrollRange(RecyclerView.State state) { return mTotalHeight; } } ``` 使用时只需要将RecyclerView的LayoutManager设置为自定义的FlowLayoutManager即可实现流式布局
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值