Android RecyclerView 网格布局 实现分割线宽度相同

转载自:https://www.it610.com/article/1289321582728126464.htm

工具类:
public class GridSpacingItemDecoration extends RecyclerView.ItemDecoration {

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

public GridSpacingItemDecoration(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) {
    int position = parent.getChildAdapterPosition(view);
    int column = position % spanCount;
    if (includeEdge) {
        outRect.left = spacing - column * spacing / spanCount;
        outRect.right = (column + 1) * spacing / spanCount;
        if (position < spanCount) {
            outRect.top = spacing;
        }
        outRect.bottom = spacing;
    } else {
        outRect.left = column * spacing / spanCount;
        outRect.right = spacing - (column + 1) * spacing / spanCount;

// if (position >= spanCount) {
// outRect.top = spacing;
// }
if (position < spanCount) {
outRect.top = spacing;
}
outRect.bottom = spacing;
}
}
}

使用方式:
recyclerview.addItemDecoration(new GridSpacingItemDecoration(2, 30, true));
recyclerview.setHasFixedSize(true);

ITEM布局:

android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">





    
    
    
    


你可能感兴趣的:(Android RecyclerView 网格布局 实现分割线宽度相同)