一个自定义RecyclerView.LayoutManager



public class PaddingLayoutManager extends RecyclerView.LayoutManager {

    /**
     * constant
     */
    private static final String TAG = "PaddingLayoutManager";
    private static final int ITEM_WIDTH = DeviceUtil.getScreenWidth() / 5;//child view卡片宽度

    /**
     * data
     */
    private SparseArray mAllRectList = new SparseArray<>();//用于保存item的位置信息
    private SparseBooleanArray mAllStateList = new SparseBooleanArray();//用于保存item是否处于可见状态的信息
    private int mTotalWidth = 0;
    private int mAllOffset = 0;

    /**
     * 获取当前居中的位置
     */
    public int getMiddlePos() {
        int prePos = mAllOffset / ITEM_WIDTH;
        int restOffset = mAllOffset % ITEM_WIDTH;

        //超过一半认为是下一个卡片
        if (restOffset >= ITEM_WIDTH / 2) {
            prePos += 1;
        }
        return prePos + 2;
    }

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

    @Override
    public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
        Log.w(TAG, "onLayoutChildren");
        if (getItemCount() <= 0 || state.isPreLayout()) {
            return;
        }
        //getItemCount()方法会调用adapter的getItemCount()方法,所以他获取到的是数据的总数,而getChildCount()方法则是获取当前已添加了的子View的数量。
        if (getChildCount() == 0) {
            //先把所有的View先从RecyclerView中detach掉,然后标记为"Scrap"状态,表示这些View处于可被重用状态(非显示中)。实际就是把View放到了Recycler中的一个集合中
            detachAndScrapAttachedViews(recycler);
            calculateChildrenSite(recycler, state);
        }
    }

    /**
     * 初始化计算并保存每个ItemView的位置
     */
    private void calculateChildrenSite(RecyclerView.Recycler recycler, RecyclerView.State state) {
        //计算位置
        for (int i = 0; i < getItemCount(); i++) {
            View view = recycler.getViewForPosition(i);
            addView(view);//刚刚进行了detach操作,所以重新添加
            //指定ItemView的尺寸。默认为measureChildWithMargins(view, 0, 0);
            measureChildWithMargins(view, ITEM_WIDTH, 0);
            //调整ItemView的大小,以除去ItemDecorator。
            calculateItemDecorationsForChild(view, new Rect());

            //设置child view的位置
            Rect tempRect = mAllRectList.get(i);
            if (tempRect == null) {
                tempRect = new Rect();
            }
            int width = getDecoratedMeasuredWidth(view);
            tempRect.set(mTotalWidth, 0, mTotalWidth + width, getHeight());
            mTotalWidth += width;

            //保存ItemView的位置信息,之前调用过detachAndScrapAttachedViews(recycler),此时item都是不可见
            mAllRectList.put(i, tempRect);
            mAllStateList.put(i, false);
        }
        //放置位置
        recycleAndFillView(recycler, state);
    }

    @Override
    public int scrollVerticallyBy(int dy, RecyclerView.Recycler recycler, RecyclerView.State state) {
        return super.scrollVerticallyBy(dy, recycler, state);
    }

    @Override
    public int scrollHorizontallyBy(int dx, RecyclerView.Recycler recycler, RecyclerView.State state) {
        //每次滑动时先释放掉所有的View,后面调用recycleAndFillView()时重新addView()。
        detachAndScrapAttachedViews(recycler);
        //向下滑动dy为正,向右滑动dx为正
        int travel = dx;//实际滑动的距离

        //滑动到最左
        if (mAllOffset + dx < 0) {
            travel = -mAllOffset;
            //滑动到最右
        } else if (mAllOffset + dx > mTotalWidth - getHorizontalSpace()) {
            travel = mTotalWidth - getHorizontalSpace() - mAllOffset;
        }
        // 调用该方法通知view在x方向上移动指定距离
        offsetChildrenHorizontal(-travel);
        recycleAndFillView(recycler, state); //回收并显示View
        // 将水平方向的偏移量+travel
        mAllOffset += travel;
        return travel;
    }

    /**
     * 放置item
     */
    private void recycleAndFillView(RecyclerView.Recycler recycler, RecyclerView.State state) {
        if (getItemCount() <= 0 || state.isPreLayout()) {
            return;
        }

        // 当前scroll offset状态下的显示区域
        Rect displayRect = new Rect(mAllOffset, 0, mAllOffset + getHorizontalSpace(), getVerticalSpace());

        //将滑出屏幕的Items回收到Recycle缓存中
        Rect childRect = new Rect();
        for (int i = 0; i < getChildCount(); i++) {
            //这个方法获取的是RecyclerView中的View,注意区别Recycler中的View
            //这获取的是实际的View
            View child = getChildAt(i);
            //下面几个方法能够获取每个View占用的空间的位置信息,包括ItemDecorator
            if (child != null) {
                childRect.left = getDecoratedLeft(child);
                childRect.top = getDecoratedTop(child);
                childRect.right = getDecoratedRight(child);
                childRect.bottom = getDecoratedBottom(child);
            }
            //如果Item没有在显示区域,就说明需要回收
            if (!Rect.intersects(displayRect, childRect)) {
                //移除并回收掉滑出屏幕的View
                if (child != null) {
                    removeAndRecycleView(child, recycler);
                }
                mAllStateList.put(i, false); //更新该View的状态为未依附
            }
        }

        //重新显示需要出现在屏幕的子View
        for (int i = 0; i < getItemCount(); i++) {
            //判断ItemView的位置和当前显示区域是否重合
            if (Rect.intersects(displayRect, mAllRectList.get(i))) {
                //获得Recycler中缓存的View
                View itemView = recycler.getViewForPosition(i);
                measureChildWithMargins(itemView, ITEM_WIDTH, 0);
                //添加View到RecyclerView上
                addView(itemView);
                //取出先前存好的ItemView的位置矩形
                Rect rect = mAllRectList.get(i);
                //将这个item布局出来,计算每个item中心点距离屏幕中心的距离,以此距离对y轴进行同比例计算
                int itemMiddle = (rect.left + rect.right - 2 * mAllOffset) / 2;
                int itemXOffSet = Math.abs(DeviceUtil.getScreenWidth() / 2 - itemMiddle);
                int itemYOffset = (int) ((itemXOffSet * 1.0f / (DeviceUtil.getScreenWidth() / 2)) * (getHeight() - 40));
                layoutDecoratedWithMargins(itemView, rect.left - mAllOffset, rect.top - itemYOffset, rect.right - mAllOffset, rect.bottom - itemYOffset);
                mAllStateList.put(i, true); //更新该View的状态为依附
            }
        }
    }

    @Override
    public boolean canScrollHorizontally() {
        //返回true表示可以横向滑动
        return true;
    }

    @Override
    public boolean canScrollVertically() {
        //返回true表示可以纵向滑动
        return super.canScrollVertically();
    }

    /**
     * 计算RecyclerView的可用高度(视觉可见),除去上下Padding值
     */
    private int getVerticalSpace() {
        return getHeight() - getPaddingBottom() - getPaddingTop();
    }

    /**
     * 计算RecyclerView的可用宽度(视觉可见),除去左右Padding值
     */
    private int getHorizontalSpace() {
        return getWidth() - getPaddingLeft() - getPaddingRight();
    }
}

 

你可能感兴趣的:(android)