package com.usai.redant.raimage.PhotoList;


import android.graphics.Rect;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;


public class GridItemDecoration extends RecyclerView.ItemDecoration {


    private int spanCount;
    private int spacing;
    private boolean includeEdge;

    public GridItemDecoration(int spanCount, int spacing, boolean includeEdge) {
        this.spanCount = spanCount;
        this.spacing = spacing;
        this.includeEdge = includeEdge;
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {



        GridLayoutManager layoutManager = (GridLayoutManager) parent.getLayoutManager();
        //判断总的数量是否可以整除
        int totalCount = layoutManager.getItemCount();
        int columns = layoutManager.getSpanCount();// 列
        int rowCount = totalCount % columns; // 行
        int childPosition = parent.getChildAdapterPosition(view); // 当前位置

        if (layoutManager.getOrientation() == GridLayoutManager.VERTICAL) {//竖直方向的

            if (childPosition > rowCount * layoutManager.getSpanCount()) { // 最后一行
                outRect.bottom = spacing;
            } else if (childPosition % layoutManager.getSpanCount() == layoutManager.getSpanCount() - 1) { // 最后一列
                outRect.right = spacing;
            }
            outRect.top = spacing;
            outRect.left = spacing;

        } else {
            if (rowCount == 0 && childPosition > totalCount - layoutManager.getSpanCount() - 1) {
                //后面几项需要右边
                outRect.right = spacing;
            } else if (rowCount != 0 && childPosition > totalCount - rowCount - 1) {
                outRect.right = spacing;
            }
            if ((childPosition + 1) % layoutManager.getSpanCount() == 0) {//被整除的需要下边
                outRect.bottom = spacing;
            }
            outRect.top = spacing;
            outRect.left = spacing;
        }

    }

}