自定义LayoutManager简明教程

自定义LayoutManager的步骤:

总体可分为四步:

  1. 重写generateDefaultLayoutParams()
  2. 重写 onLayoutChildren()
  3. 重写 canScrollVertically() 或者 canScrollHorizontally()
  4. 重写 scrollHorizontallyBy() 或者 scrollVerticallyBy()

这些都是些什么。别慌,一步步来,下面会以可横向滚动layoutManager来一一解释这些方法。首先得注意无论是在onLayoutChildren、scrollHorizontallyBy() 或者 scrollVerticallyBy()RecyclerView只会layout出可见的childview,不可见的childView会被移除、回收掉

步骤1
  • 方法解释
    generateDefaultLayoutParams():为RecyclerView的子View(也就是我们常说的Itme)创建一个默认的LayoutParams对象

    SDK 解释如下
    Create a default LayoutParams object for a child of the RecyclerView.

  • 实现,没有特殊要求如下实现方式即可

@Override
    public RecyclerView.LayoutParams generateDefaultLayoutParams() {
        return new RecyclerView.LayoutParams(
                RecyclerView.LayoutParams.WRAP_CONTENT,
                RecyclerView.LayoutParams.WRAP_CONTENT);
    }
步骤2
  • 方法解释
    onLayoutChildren():从给定适配器设置所有相关的子视图.在初始化或者调用notifyDataSetChanged()时调用该方法,只需要layout 显示的childView即可

    SDK 解释如下
    Lay out all relevant child views from the given adapter

  • 实现

  1. 常量、变量解释
 //RecyclerView从右往左滑动时,新出现的child添加在右边
    private static int ADD_RIGHT = 1;
    //RecyclerView从左往右滑动时,新出现的child添加在左边
    private static int ADD_LEFT = -1;
    //SDK中的方法,帮助我们计算一些layout childView 所需的值,详情看源码,解释的很明白
    private OrientationHelper helper;
    //动用 scrollToPosition 后保存去到childView的位置,然后重新布局即调用onLayoutChildren
    private int mPendingScrollPosition = 0;
  1. onLayoutChildren 实现
    public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
        if (getItemCount() == 0) {
            detachAndScrapAttachedViews(recycler);
            return;
        }
        if (getChildCount() == 0 && state.isPreLayout()) {
            return;
        }
        //初始化OrientationHelper
        ensureStatus();
        int offset = 0;
        //计算RecyclerView 可用布局宽度  具体实现 mLayoutManager.getWidth() - mLayoutManager.getPaddingLeft()
        //- mLayoutManager.getPaddingRight();
        int mAvailable = helper.getTotalSpace();
        //调用notifyDataSetChanged 才有 getChildCount() != 0
        if (getChildCount() != 0) {
            //得到第一个可见的childView
            View firstView = getChildAt(0);
            //得到第一个可见childView左边的位置
            offset = helper.getDecoratedStart(firstView);
            //获取第一个可见childView在Adapter中的position(位置)
            mPendingScrollPosition = getPosition(firstView);
            //offset的值为负数,在可见区域的左边,那么当重新布局事得考虑正偏移
            mAvailable += Math.abs(offset);
        }
        //移除所有的view,
        detachAndScrapAttachedViews(recycler);
        //将可见区域的childView layout出来
        layoutScrap(recycler, state, offset, mAvailable);
    }
  1. 初始化OrientationHelper
private void ensureStatus() {
        if (helper == null) {
            helper = OrientationHelper.createHorizontalHelper(this);
        }
    }
  1. 将可见区域的childView layout出来
/**
     * 将可见区域的childView layout出来
     */
    private void layoutScrap(RecyclerView.Recycler recycler, RecyclerView.State state, int offset, int mAvailable) {
        for (int i = mPendingScrollPosition; i < state.getItemCount(); i++) {
            //可用布局宽度不足,跳出循环
            if (mAvailable <= 0) {
                break;
            }
            //在右边添加新的childView
            int childWidth = layoutScrapRight(recycler, i, offset);
            mAvailable -= childWidth;
            offset += childWidth;
        }
    }
  1. 添加新的childView
 /**
     *  RecyclerView从右往左滑动时,新出现的child添加在右边
     */
    private int layoutScrapRight(RecyclerView.Recycler recycler, int position, int offset) {
        return layoutScrap(recycler, position, offset, ADD_RIGHT);
    }

    /**
     *  RecyclerView从右往左滑动时,新出现的child添加在右边
     */
    private int layoutScrapleft(RecyclerView.Recycler recycler, int position, int offset) {
        return layoutScrap(recycler, position, offset, ADD_LEFT);
    }

    /**
     *  RecyclerView从右往左滑动时,添加新的child
     */
    private int layoutScrap(RecyclerView.Recycler recycler, int position, int offset, int direction) {
        //从 recycler 中取到将要出现的childView
        View childPosition = recycler.getViewForPosition(position);
        if (direction == ADD_RIGHT) {
            addView(childPosition);
        } else {
            addView(childPosition, 0);
        }
        //计算childView的大小
        measureChildWithMargins(childPosition, 0, 0);
        int childWidth = getDecoratedMeasuredWidth(childPosition);
        int childHeigth = getDecoratedMeasuredHeight(childPosition);
        if (direction == ADD_RIGHT) {
            //layout childView
            layoutDecorated(childPosition, offset, 0, offset + childWidth, childHeigth);
        } else {
            layoutDecorated(childPosition, offset - childWidth, 0, offset, childHeigth);
        }
        return childWidth;
    }
步骤3
  • 方法解释
    canScrollVertically():竖直方向是否可以滚动
    canScrollHorizontally():水平方向是否可以滚动

  • 实现 ,本例只实现canScrollHorizontally

@Override
    public boolean canScrollHorizontally() {
        return true;
    }
步骤4
  • 方法解释
    scrollVerticallyBy():处理竖直方向滚动时不可见的childView的回收,新出现childview的添加
    scrollHorizontallyBy():处理水平方向滚动时不可见的childView的回,收新出现childview的添加

  • 实现 ,本例只实现scrollHorizontallyBy

 @Override
    public int scrollHorizontallyBy(int dx, RecyclerView.Recycler recycler, RecyclerView.State state) {
        //回收不可见的childview
        recylerUnVisiableView(recycler, dx);
        //将新出现的childview layout 出来
        int willScroll = fillChild(recycler, dx, state);
        //水平方向移动childview
        offsetChildrenHorizontal(-willScroll);
        return willScroll;
    }

    private int fillChild(RecyclerView.Recycler recycler, int dx, RecyclerView.State state) {
        if (dx > 0) {//RecyclerView从右往左滑动时
            //得到最后一个可见childview
            View lastView = getChildAt(getChildCount() - 1);
            //得到将显示的childView 在adapter 中的position
            int position = getPosition(lastView) + 1;
            //得到最后一个可见childView右边的偏移
            int offset = helper.getDecoratedEnd(lastView);
            //判断是否有足够的空间
            if (offset - dx < getWidth() - getPaddingRight()) {
                //item 足够
                if (position < state.getItemCount()) {
                    layoutScrapRight(recycler, position, offset);
                } else {
                    //item 不足 返回新的可滚动的宽度    
                    return offset - getWidth() + getPaddingRight();
                }
            }
        } else {//RecyclerView从左往右滑动时
            //得到第一个可见childview
            View firstView = getChildAt(0);
            //得到将显示的childView 在adapter 中的position
            int position = getPosition(firstView) - 1;
            //得到第一个可见childView左边的偏移
            int offset = helper.getDecoratedStart(firstView);
            //判断是否有足够的空间
            if (offset - dx > getPaddingLeft()) {
                //item 足够
                if (position >= 0) {
                    layoutScrapleft(recycler, position, offset);
                } else {
                    //item 不足 返回新的可滚动的宽度  
                    return offset - getPaddingLeft();
                }
            }
        }
        return dx;
    }

    /**
     * 回收不可见的childview
     */
    private void recylerUnVisiableView(RecyclerView.Recycler recycler, int dx) {
        for (int i = 0; i < getChildCount(); i++) {
            View child = getChildAt(i);
            if (dx > 0) {//RecyclerView从右往左滑动时
                //将左边消失的childView 回收掉
                if (helper.getDecoratedEnd(child) - dx < getPaddingLeft()) {
                    removeAndRecycleView(child, recycler);
                    break;
                }
            } else {//RecyclerView从左往右滑动时
                //将右边的childView 回收掉
                if (helper.getDecoratedStart(child) - dx > getWidth() - getPaddingRight()) {
                    removeAndRecycleView(child, recycler);
                    break;
                }
            }
        }
    }
扩展
  • scrollToPosition 滑动到指定位置,调用该方法后,会调用onLayoutChildren
@Override
    public void scrollToPosition(int position) {
        super.scrollToPosition(position);
        mPendingScrollPosition = position;
        requestLayout();
    }
  • smoothScrollToPosition 缓慢的滚动到指定位置
 @Override
    public void smoothScrollToPosition(RecyclerView recyclerView, RecyclerView.State state, int position) {
        LinearSmoothScroller linearSmoothScroller =
                new LinearSmoothScroller(recyclerView.getContext()) {
                    @Nullable
                    @Override
                    public PointF computeScrollVectorForPosition(int targetPosition) {
                        if (getChildCount() == 0) {
                            return null;
                        }
                        final int firstChildPos = getPosition(getChildAt(0));
                        final int direction = targetPosition < firstChildPos ? -1 : 1;
                        return new PointF(direction, 0);
                    }
                };
        linearSmoothScroller.setTargetPosition(position);
        startSmoothScroll(linearSmoothScroller);
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,835评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,598评论 1 295
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,569评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,159评论 0 213
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,533评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,710评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,923评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,674评论 0 203
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,421评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,622评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,115评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,428评论 2 254
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,114评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,097评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,875评论 0 197
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,753评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,649评论 2 271

推荐阅读更多精彩内容

  • 简介: 提供一个让有限的窗口变成一个大数据集的灵活视图。 术语表: Adapter:RecyclerView的子类...
    酷泡泡阅读 5,055评论 0 16
  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,663评论 0 33
  • ViewDragHelper实例的创建 ViewDragHelper重载了两个create()静态方法public...
    傀儡世界阅读 632评论 0 3
  • 这篇文章分三个部分,简单跟大家讲一下 RecyclerView 的常用方法与奇葩用法;工作原理与ListView比...
    LucasAdam阅读 4,320评论 0 27
  • 自我的解析 是了解孤独的第一步 当你沉淀了一段感情 四下无人的夜里 终会释放 此时孤独被你提起 此时孤独需要你的陪...
    朴质的骚话阅读 192评论 0 1