不知道怎么,自己最近的时间老是不想学习,又开始玩一起来了,又在莫名的幻想一起没有用的东西。今天我把我忘记的东西下下来啊,以后在用的时候不用再去翻别人的博客自己博客有那不很好。
给指定的item设置间距,
首页写一个类
pubulic class RecyclerView extends ReyclerView.ItemDecoration{
//定义局部变量
private int space;
//创建构造起
public RecyclerView(int space){
初始化变量
this.space=space;
}
重写方法
getitemoffsets
@Override
public void getItemOffsets(Rect outRect, View view,
RecyclerView parent, RecyclerView.State state) {
outRect.left = space;
outRect.right = space;
outRect.bottom = space;
// Add top margin only for the first item to avoid double space between items
if (parent.getChildPosition(view) == 0)
outRect.top = space;
}
}
上面是写的LinearLayoutManager
这里是GridLayoutManager或者StaggeredGridLayoutManager 设置Item间距的办法
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); // item position
int column = position % spanCount; // item column
if (includeEdge) {
outRect.left = spacing - column * spacing / spanCount; // spacing - column * ((1f / spanCount) * spacing)
outRect.right = (column + 1) * spacing / spanCount; // (column + 1) * ((1f / spanCount) * spacing)
if (position < spanCount) { // top edge
outRect.top = spacing;
}
outRect.bottom = spacing; // item bottom
} else {
outRect.left = column * spacing / spanCount; // column * ((1f / spanCount) * spacing)
outRect.right = spacing - (column + 1) * spacing / spanCount; // spacing - (column + 1) * ((1f / spanCount) * spacing)
if (position >= spanCount) {
outRect.top = spacing; // item top
}
}
}
}
调用
int spanCount = 3; // 3 columns int spacing = 50; // 50px boolean includeEdge = false;
mRecyclerView.addItemDecoration(new GridSpacingItemDecoration(spanCount, spacing, includeEdge));