使用RecyclerView实现每三行一个间距并且带分隔符

找不到当初的UI图了 只能做了个Demo截了个图。样子大概就是图中的样子。(不知道为什么图一直是横着的)

先说说需求吧,一行要求三个行业,每三行成为一个小分组,间距大概为普通间距 * 5,每个小行业后面带一个分割线,小分组的最后一个不带。

我最开始的想法是用 ListView 内部嵌套 GridView 来完成(偷懒的想法),当然 结果肯定不怎么样,不然也不会有这篇文章了。然后想到了RecyclerView,毕竟RecyclerView就是用来干这个的,自由度相对于其他的流式控件要高很多

RecyclerView 里面有个专门用来设置分割线的方法

public void addItemDecoration(ItemDecoration decor) {
    addItemDecoration(decor, -1);
}

一些具体RecyclerView 的配置与应用可以参考 HongYang大神的文章 虽然这文章已经比较老了

https://blog.csdn.net/lmj623565791/article/details/45059587

其他的方法都与上面文章里的没有太大出入,只是根据自己的需求做了些修改。主要改动还是在

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

在这个方法可以根据自己的需求,用不同的算法来实现自己所想要的效果

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

    int spanCount = getSpanCount(parent);
    int childLayoutPosition = parent.getChildLayoutPosition(view);
    int line = (childLayoutPosition / 3) + 1;
    if (line % 3 == 0) {
        outRect.bottom = mCenterHorzentalSpace * 5;
    } else {
        outRect.bottom = mCenterHorzentalSpace;
    }
    int childCount = parent.getAdapter().getItemCount();
    if (isLastRaw(parent, childLayoutPosition, spanCount, childCount))
    {
        outRect.bottom = 0;
    } else if (isLastColum(parent, childLayoutPosition, spanCount, childCount))
        outRect.right = 0;
    }
}

public class DividerGridItemDecoration extends RecyclerView.ItemDecoration {
    private static final int[] ATTRS = new int[]{android.R.attr.listDivider};
    private Drawable mDivider;

    private int mLeftRightSpace;
    private int mCenterHorzentalSpace;
    private int mCenterVerticalSpace;

    public DividerGridItemDecoration(int mLeftRightSpace, int mCenterHorzentalSpace, int mCenterVerticalSpace, Activity activity) {
        final TypedArray a = activity.obtainStyledAttributes(ATTRS);
        mDivider = a.getDrawable(0);
        a.recycle();
        this.mLeftRightSpace = mLeftRightSpace;
        this.mCenterHorzentalSpace = mCenterHorzentalSpace;
        this.mCenterVerticalSpace = mCenterVerticalSpace;
    }
recyclerView.addItemDecoration(new DividerGridItemDecoration(10,4,10,getActivity()));

搞定。

(横向分割线的代码有点问题所以暂时没贴出来 如果那里有问题希望指出,交流进步)

猜你喜欢

转载自blog.csdn.net/qq_32155895/article/details/80251316