改造LayoutManager实现不一样的列表效果

1.前言

    我们都知道,对于RecyclerView而言,android自带的有三种类型的LayoutManager,分别是LinearLayoutManagr(线性布局器),GridLayoutManager(网格布局器)和StaggeredGridLayoutManager(瀑布流布局器)。然而在实际的开发过程中,这三种往往不能够满足实际效果的需要,那么就需要开发者自己去打造自己的LayoutManager。网上找了很多篇的博客和文章,自己研究并实现了下如下的效果,在这里分享给大家。


demo.gif

2.RecyclerView机制

    要想打造属于自己的LayoutManager,首先得了解下RecyclerView的机制是什么样的。关于RecyclerView的机制是什么样的以及最基础的LayoutManager的改造方法,大家可以看csdn地址http://blog.csdn.net/huachao1001/article/details/51594004 这篇文章。这篇是我看的文章里面描述最详细的。我在这边主要讲述如何实现上述的效果

3.效果的分析

    从上面的列表效果可以看出,RecyclerView支持的是左右进行滑动,滑动方式是沿着一条曲线进行,并且在经过中心位置的时候item有个放大缩小的效果。那么从列表的布局来看,我们可以将其排布在一个圆形弧线上,中心位置的角度为0度,左侧递减,右侧递增,那么每个item的位置就在对应的角度上。然后在经过0度区域时(可以是-30--30或者其他),对item进行放大缩小操作,可以使用 view.setScaleX()和 view.setScaleY(scale)方法。

4.效果的实现

  4.1 开始自定义LayoutManager

    首先将我们自己的CustomLayoutManager继承RecyclerView.LayoutManager,实现抽象类RecyclerView.LayoutManager里面的抽象方法generateDefaultLayoutParams(),实现如下

@Overridepublic RecyclerView.LayoutParams generateDefaultLayoutParams() {  
  return new RecyclerView.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
}

    当然光重写上述的方法并没有什么效果,我们还要重写LayoutManager
的onLayoutChildren()方法,这个方法从名称就可以看出来是对子view的一个布局,要实现上面的图片效果,自然需要对应的代码支持

 @Override
    public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
        //如果没有item,直接返回
        //跳过preLayout,preLayout主要用于支持动画
        if (getItemCount() <= 0 || state.isPreLayout()) {
            offsetRotate = 0;
            return;
        }
       //得到子view的宽和高,这边的item的宽高都是一样的,所以只需要进行一次测量
       View scrap = recycler.getViewForPosition(0);
       addView(scrap);
       measureChildWithMargins(scrap, 0, 0);
       //计算测量布局的宽高
       mDecoratedChildWidth = getDecoratedMeasuredWidth(scrap);
       mDecoratedChildHeight = getDecoratedMeasuredHeight(scrap);
       //确定起始位置,在最上方的中心处
       startLeft = (getHorizontalSpace() - mDecoratedChildWidth) / 2;
       startTop = 0;
        
        //记录每个item旋转的角度
        float rotate = firstChildRotate;
        for (int i = 0; i < getItemCount(); i++) {
            itemsRotate.put(i, rotate);
            itemAttached.put(i, false);
            rotate += intervalAngle;
        }
        //在布局之前,将所有的子View先Detach掉,放入到Scrap缓存中
        detachAndScrapAttachedViews(recycler);
        fixRotateOffset();
        layoutItems(recycler, state);
    }

    从上面的代码可以看出,因为在这里每个item的大小都是一致的,所以我们只需要测量一次得到item的宽高之后的item就可以直接使用。然后还需要确定最中心的item的位置,这里是startLeft和startTop。然后对每个item进行角度的保存和处理,如下

   /**
     * 默认每个item之间的角度
     **/
    private static float INTERVAL_ANGLE = 30f;
   /**
     * 第一个的角度是为0
     **/
    private int firstChildRotate = 0;
    /**
     * 第一个的角度是为0
     **/
    private int firstChildRotate = 0;
   //最大和最小的移除角度
    private int minRemoveDegree;
    private int maxRemoveDegree;

    //记录Item是否出现过屏幕且还没有回收。true表示出现过屏幕上,并且还没被回收
    private SparseBooleanArray itemAttached = new SparseBooleanArray();
    //保存所有的Item的上下左右的偏移量信息
    private SparseArray<Float> itemsRotate = new SparseArray<>();

    /**
     * 设置滚动时候的角度
     **/
    private void fixRotateOffset() {
        if (offsetRotate < 0) {
            offsetRotate = 0;
        }
        if (offsetRotate > getMaxOffsetDegree()) {
            offsetRotate = getMaxOffsetDegree();
        }
    }

    上述代码的作用是对每个item位置的一个记录和item是否显示的一个记录,offsetRotate 保存当前item布局的一个角度总量,将其限制在一个范围之内。在范围内的item用于显示,之外的进行回收。下面来看layoutItems()方法,该方法是对item的一个回收和显示。

/**
     * 进行view的回收和显示
     **/
    private void layoutItems(RecyclerView.Recycler recycler, RecyclerView.State state) {
        layoutItems(recycler, state, SCROLL_RIGHT);
    }

    /**
     * 进行view的回收和显示的具体实现
     **/
    private void layoutItems(RecyclerView.Recycler recycler,
                             RecyclerView.State state, int oritention) {
        if (state.isPreLayout()) return;

        //移除界面之外的view
        for (int i = 0; i < getChildCount(); i++) {
            View view = getChildAt(i);
            int position = getPosition(view);
            if (itemsRotate.get(position) - offsetRotate > maxRemoveDegree
                    || itemsRotate.get(position) - offsetRotate < minRemoveDegree) {
                itemAttached.put(position, false);
                removeAndRecycleView(view, recycler);
            }
        }

        //将要显示的view进行显示出来
        for (int i = 0; i < getItemCount(); i++) {
            if (itemsRotate.get(i) - offsetRotate <= maxRemoveDegree
                    && itemsRotate.get(i) - offsetRotate >= minRemoveDegree) {
                if (!itemAttached.get(i)) {
                    View scrap = recycler.getViewForPosition(i);
                    measureChildWithMargins(scrap, 0, 0);
                    if (oritention == SCROLL_LEFT)
                        addView(scrap, 0);
                    else
                        addView(scrap);
                    float rotate = itemsRotate.get(i) - offsetRotate;

                    int left = calLeftPosition(rotate);
                    int top =  calTopPosition(rotate);

                    scrap.setRotation(rotate);

                    layoutDecorated(scrap, startLeft + left, startTop + top,
                            startLeft + left + mDecoratedChildWidth, startTop + top + mDecoratedChildHeight);

                    itemAttached.put(i, true);

                    //计算角度然后进行放大
                    float scale = calculateScale(rotate);
                    scrap.setScaleX(scale);
                    scrap.setScaleY(scale);
                }
            }
        }
    }

    首先对于角度在范围之外的item进行remove掉,对于范围之内的item,通过layoutDecorated()方法进行显示,根据左滑还是右滑,判断item显示的位置。同时根据当前item的角度位置,判断当前item是否需要进行放大或者缩小,计算方法如下。

    /**
     * 最大放大倍数
     **/
    private static final float SCALE_RATE = 1.4f;
    //放大的倍数
    private float maxScale;
    //在什么角度变化之内
    private float minScaleRotate = 40;
    /**
     * 默认每个item之间的角度
     **/
    private static float INTERVAL_ANGLE = 30f;
    /**
     * 默认的半径长度
     **/
    private static final int DEFAULT_RADIO = 100;
    /**
     * 半径默认为100
     **/
    private int mRadius;
    /**
     * 根据角度计算大小,0度的时候最大,minScaleRotate度的时候最小,然后其他时候变小
     **/
    private float calculateScale(float rotate) {
        rotate = Math.abs(rotate) > minScaleRotate ? minScaleRotate : Math.abs(rotate);
        return (1 - rotate / minScaleRotate) * (maxScale - 1) + 1;
    }

    /**
     * 当前item的x的坐标
     **/
    private int calLeftPosition(float rotate) {
        return (int) (mRadius * Math.cos(Math.toRadians(90 - rotate)));
    }

    /**
     * 当前item的y的坐标
     **/
    private int calTopPosition(float rotate) {
        return (int) (mRadius * Math.sin(Math.toRadians(90 - rotate)));
    }

经过以上的步骤,该RecyclerView已经能够进行列表显示了,但是还不能够进行滑动。

  4.2 LayoutManager实现滑动

    LayoutManager中还有canScrollHorizontally()和canScrollVertically()分别代表是否可以进行横向和纵向的滑动。
同时还有scrollHorizontallyBy和scrollVerticallyBy方法来实现对应的逻辑。这边我们需要的是进行横向的滑动,那么实现方法如下

  @Override
    public boolean canScrollHorizontally() {
        return true;
    }
@Override
    public int scrollHorizontallyBy(int dx, RecyclerView.Recycler recycler, RecyclerView.State state) {
        int willScroll = dx;

        //每个item x方向上的移动距离
        float theta = dx / DISTANCE_RATIO;
        float targetRotate = offsetRotate + theta;

        //目标角度
        if (targetRotate < 0) {
            willScroll = (int) (-offsetRotate * DISTANCE_RATIO);
        } else if (targetRotate > getMaxOffsetDegree()) {
            willScroll = (int) ((getMaxOffsetDegree() - offsetRotate) * DISTANCE_RATIO);
        }
        theta = willScroll / DISTANCE_RATIO;

        //当前移动的总角度
        offsetRotate += theta;

        //重新设置每个item的x和y的坐标
        for (int i = 0; i < getChildCount(); i++) {
            View view = getChildAt(i);
            float newRotate = view.getRotation() - theta;
            int offsetX = calLeftPosition(newRotate);
            int offsetY =  calTopPosition(newRotate);

            layoutDecorated(view, startLeft + offsetX, startTop + offsetY,
                    startLeft + offsetX + mDecoratedChildWidth, startTop + offsetY + mDecoratedChildHeight);
            view.setRotation(newRotate);

            //计算角度然后进行放大
            float scale = calculateScale(newRotate);
            view.setScaleX(scale);
            view.setScaleY(scale);
        }

        //根据dx的大小判断是左滑还是右滑
        if (dx < 0)
            layoutItems(recycler, state, SCROLL_LEFT);
        else
            layoutItems(recycler, state, SCROLL_RIGHT);
        return willScroll;
    }

    可以看出来scrollHorizontallyBy()里面的操作类似与layoutItem()方法中的操作,只不过在这里需要对横向滚动量dx进行角度的装换,这边给的比例为DISTANCE_RATIO,然后需要对offsetRotate进行累加操作,最后调用layoutItems进行item的view的回收和显示。经过以上的操作,RecyclerView就可以进行列表的展示和滑动了。

   4.3 RecyclerView的自行滚动到某一项

    需要注意的是,由于我们已经修改了LayoutManager的滚动规则。

     /**
     * Convenience method to scroll to a certain position.
     *
     * RecyclerView does not implement scrolling logic, rather forwards the call to
     * {@link android.support.v7.widget.RecyclerView.LayoutManager#scrollToPosition(int)}
     * @param position Scroll to this adapter position
     * @see android.support.v7.widget.RecyclerView.LayoutManager#scrollToPosition(int)
     */
    public void scrollToPosition(int position) {
        if (mLayoutFrozen) {
            return;
        }
        stopScroll();
        if (mLayout == null) {
            Log.e(TAG, "Cannot scroll to position a LayoutManager set. " +
                    "Call setLayoutManager with a non-null argument.");
            return;
        }
        mLayout.scrollToPosition(position);
        awakenScrollBars();
    }

/**
     * Starts a smooth scroll to an adapter position.
     * <p>
     * To support smooth scrolling, you must override
     * {@link LayoutManager#smoothScrollToPosition(RecyclerView, State, int)} and create a
     * {@link SmoothScroller}.
     * <p>
     * {@link LayoutManager} is responsible for creating the actual scroll action. If you want to
     * provide a custom smooth scroll logic, override
     * {@link LayoutManager#smoothScrollToPosition(RecyclerView, State, int)} in your
     * LayoutManager.
     *
     * @param position The adapter position to scroll to
     * @see LayoutManager#smoothScrollToPosition(RecyclerView, State, int)
     */
    public void smoothScrollToPosition(int position) {
        if (mLayoutFrozen) {
            return;
        }
        if (mLayout == null) {
            Log.e(TAG, "Cannot smooth scroll without a LayoutManager set. " +
                    "Call setLayoutManager with a non-null argument.");
            return;
        }
        mLayout.smoothScrollToPosition(this, mState, position);
    }

    而从源码中可以看出来RecyclerView的scrollToPosition()(滚动到某一项),
smoothScrollToPosition()(平滑滚动到某一项)其实是调用的layoutManager中对于的方法,所以我们必须重写我们自己的layoutManager的对于的方法,实现自己的滚动规则。

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


    @Override
    public void scrollToPosition(int position) {//移动到某一项
        if (position < 0 || position > getItemCount() - 1) return;
        float targetRotate = position * intervalAngle;
        if (targetRotate == offsetRotate) return;
        offsetRotate = targetRotate;
        fixRotateOffset();
        requestLayout();
    }

    @Override
    public void smoothScrollToPosition(RecyclerView recyclerView, RecyclerView.State state, int position) {//平滑的移动到某一项
        LinearSmoothScroller smoothScroller = new LinearSmoothScroller(recyclerView.getContext()) {
            @Override
            public PointF computeScrollVectorForPosition(int targetPosition) {
                return CustomLayoutManager.this.computeScrollVectorForPosition(targetPosition);
            }
        };
        smoothScroller.setTargetPosition(position);
        startSmoothScroll(smoothScroller);
    }

    在scrollToPosition中,我们需要根据position获取对应的item在最开始布局时候的角度,赋值给offsetRotate ,让其进行重新布局即可以实现效果。而在smoothScrollToPosition()中,参考LinearLayoumanager中对应的方法。

 @Override
    public void smoothScrollToPosition(RecyclerView recyclerView, RecyclerView.State state,
            int position) {
        LinearSmoothScroller linearSmoothScroller =
                new LinearSmoothScroller(recyclerView.getContext());
        linearSmoothScroller.setTargetPosition(position);
        startSmoothScroll(linearSmoothScroller);
    }

    @Override
    public PointF computeScrollVectorForPosition(int targetPosition) {
        if (getChildCount() == 0) {
            return null;
        }
        final int firstChildPos = getPosition(getChildAt(0));
        final int direction = targetPosition < firstChildPos != mShouldReverseLayout ? -1 : 1;
        if (mOrientation == HORIZONTAL) {
            return new PointF(direction, 0);
        } else {
            return new PointF(0, direction);
        }
    }

    从computeScrollVectorForPosition可以知道,对于我们自己的LayoutManager而言
从前面的item滚动到后面的是new PointF(-1, 0);相反的就是new PointF(1, 0);最后我们重写onAdapterChanged()方法,当adapter发生变化的时候,让我们自己的layoutmanager回归原始的状态。

  @Override
    public void onAdapterChanged(RecyclerView.Adapter oldAdapter, RecyclerView.Adapter newAdapter) {//adapter进行改变的时候
        removeAllViews();
        offsetRotate = 0;
    }

5.最后

    只要了解了RecyclerView的机制和RecyclerView.LayoutManager中需要实现的方法和步奏,那么对于我们自己来说,打造自己的LayoutManager并不是一件很难的事情。我在实现的过程中,主要参考了
csdn huachao1001的文章http://blog.csdn.net/huachao1001/article/details/51594004
简书Dajavu的文章http://www.jianshu.com/p/7bb7556bbe10 ,最终实现上面的效果,
最后奉上Github上代码下载地址https://github.com/hzl123456/CustomLayoutManager

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 160,108评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,699评论 1 296
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,812评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,236评论 0 213
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,583评论 3 288
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,739评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,957评论 2 315
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,704评论 0 204
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,447评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,643评论 2 249
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,133评论 1 261
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,486评论 3 256
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,151评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,108评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,889评论 0 197
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,782评论 2 277
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,681评论 2 272

推荐阅读更多精彩内容