GridLayoutManager設(shè)置一個(gè)3列列表的間距咧虎,左右貼邊闺属,中間居中稚瘾。
由于RecyclerView會(huì)將寬自動(dòng)填充滿(mǎn)牡昆,因此每個(gè)item的右邊都會(huì)留有空白部分,又由于是3列,所以
位移間距 = (屏幕寬度 - 每個(gè)item的寬度 * 3)/ 6
int screenWidth = ScreenUtils.getScreenWidth(mContext); //屏幕寬度
int itemWidth = SizeUtils.dp2px(mContext, 90); //每個(gè)item的寬度
mRecyclerView.addItemDecoration(new SpaceItemDecoration((screenWidth - itemWidth* 3)/6));
public class SpaceItemDecoration extends RecyclerView.ItemDecoration {
private int space; //位移間距
public SpaceItemDecoration(int space) {
this.space = space;
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
if (parent.getChildAdapterPosition(view) %3 == 0) {
outRect.left = 0; //第一列左邊貼邊
} else {
if (parent.getChildAdapterPosition(view) %3 == 1) {
outRect.left = space;//第二列移動(dòng)一個(gè)位移間距
} else {
outRect.left = space * 2;//由于第二列已經(jīng)移動(dòng)了一個(gè)間距丢烘,所以第三列要移動(dòng)兩個(gè)位移間距就能右邊貼邊柱宦,且item間距相等
}
}
if (parent.getChildAdapterPosition(view) >= 3) {
outRect.top = SizeUtils.dp2px(mContext, 10);
} else {
outRect.top = 0;
}
}
}