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; }
} }
|