发表于: 2019-01-15 22:52:51
0 1114
今天完成的事情
RecyclerView没有可以直接设置间距的属性,但看了源码之后可以发现RecyclerView有个内部类ItemDecoration,可以用ItemDecoration来装饰一个item,所以继承重写ItemDecoration就可以实现间距了。我看了以下,网上很多类似的介绍,但是大多都只考虑到LinearLayoutManager这种
这是LinearLayoutManager设置Item间距的的一个辅助类
public class SpacesItemDecoration extends RecyclerView.ItemDecoration {
private int space;
public SpacesItemDecoration(int space) {
this.space = space;
}
@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;
}
}
设置item间距
int space = 8;
mRecyclerView.addItemDecoration(new SpacesItemDecoration(spacingInPixels));
这里是GridLayoutManager或者StaggeredGridLayoutManager 设置Item间距的办法
public class SpaceItemDecoration extends RecyclerView.ItemDecoration {
int mSpace;
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
super.getItemOffsets(outRect, view, parent, state);
outRect.left = mSpace;
outRect.right = mSpace;
outRect.bottom = mSpace;
if (parent.getChildAdapterPosition(view) == 0) {
outRect.top = mSpace * 2;
}
}
public SpaceItemDecoration(int space) {
this.mSpace = space;
}
}
articleRV = (RecyclerView) mRootView.findViewById(R.id.rv_article);
articleRV.addItemDecoration(new SpaceItemDecoration(30));
明天的计划
完成影视部
评论