咸鱼

咸鱼是以盐腌渍后,晒干的鱼

0%

Android GridLayoutManager Decoration

GridLayoutManager 很少用,所以它的Decoration用法这里做一下备忘。

  • 主要记住行、列的计算,第一行、最后一行、第一列、最后一列的计算。
  • Item的布局要用 match_parent 采用自动适应的效果。
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
45
46
47
48
49
50
51
52
53
54
55
56
57
public class TestGridDecoration extends RecyclerView.ItemDecoration{

private int offset;

public TestGridDecoration(int offset) {
this.offset = offset;
}

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

int childLayoutPosition = parent.getChildLayoutPosition(view);

//每行的元素数量
int spanCount = ((GridLayoutManager)parent.getLayoutManager()).getSpanCount();

//总行数
int maxRow = state.getItemCount() / spanCount;
//所处的行号
int row = childLayoutPosition / spanCount;
//所处的列号
int column = childLayoutPosition % spanCount;


if(row == 0){
//第一行
outRect.top = 0;
outRect.bottom = 0;
}else if(row == maxRow){
//最后一行
outRect.top = offset;
outRect.bottom = offset;
}else{
//中间行
outRect.top = offset;
outRect.bottom = 0;
}


if(column == 0){
//第一列
outRect.left = offset;
outRect.right = offset / 2;
}else if(column == spanCount - 1){
//最后一列
outRect.left = offset / 2;
outRect.right = offset;
}else{
//中间列
outRect.left = offset / 2;
outRect.right = offset / 2;
}

}
}