Recyclerview设置GridLayoutManager分割线

public class GridSpaceItemDecoration extends RecyclerView.ItemDecoration {

    private int mSpanCount;//横条目数量
    private int mRowSpacing;//行间距
    private int mColumnSpacing;// 列间距

    /**
     * @param spanCount     列数
     * @param rowSpacing    行间距
     * @param columnSpacing 列间距
     */
    public GridSpaceItemDecoration(int spanCount, int rowSpacing, int columnSpacing) {
        this.mSpanCount = spanCount;
        this.mRowSpacing = rowSpacing;
        this.mColumnSpacing = columnSpacing;
    }

    @Override
    public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
        //获取当前位置
        int position = parent.getChildAdapterPosition(view); // 获取view 在adapter中的位置。
        int column = position % mSpanCount; // view 所在的列
        GridLayoutManager manager = (GridLayoutManager) parent.getLayoutManager();
        int spanCount = manager.getSpanCount();//获取每行的个数

        outRect.top = mRowSpacing;
       if (position%2==1){//当每行个数为2个时    1为左侧   2为右侧
           outRect.right=mColumnSpacing;
       }else {
           outRect.left = mColumnSpacing;
       }
    }
}

调用方法

        GridLayoutManager  manager = new GridLayoutManager(context,2);
        // 添加间距
        recyclerview.addItemDecoration(new GridSpaceItemDecoration(2,20,10));

你可能感兴趣的:(Android)