RecyclerView调节项目间间距大小

调用处直接调用

1
2
3
//设置item之间的间隔
SpacesItemDecoration decoration = new SpacesItemDecoration(8);
recyclerView.addItemDecoration(decoration);

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
class SpacesItemDecoration extends RecyclerView.ItemDecoration {

private int space;
private StaggeredGridLayoutManager.LayoutParams lp;

public SpacesItemDecoration(int space) {
this.space = space;
}

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

int position = parent.getChildAdapterPosition(view);
lp = (StaggeredGridLayoutManager.LayoutParams)view.getLayoutParams();
if (position == 0 || position==1){
outRect.top = space * 2;
} else {
outRect.top = space;
}

if (lp.getSpanIndex() == 0) {
outRect.left = space * 2;
outRect.right = space;
} else {
outRect.left = space;
outRect.right = space * 2;
}
outRect.bottom = space;

//注掉的方法总有漏网之鱼,不知为啥
// outRect.left = space;
// outRect.right = space;
// outRect.bottom = space;
// if (position == 0 || position == 1) {
// //用于设置第一行跟顶部的距离
// outRect.top = space;
// }
//
// if (lp.getSpanIndex() == 0) {
// //用于设同行两个间隔间跟其距离左右屏幕间隔相同
// outRect.right = 0;
// }
}
}