我正在使用RecyclerView与StaggeredGridLayoutManager来制作一个两列列表.但是如何在左列和右列之间设置一个右边距.我使用这个代码从顶部做出正确的边距,但是如何解决列之间的双重空格.
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 or second item to avoid double space between items
// Add top margin only for the first or second item to avoid double space between items
if((parent.getChildCount() > 0 && parent.getChildPosition(view) == 0)
|| (parent.getChildCount() > 1 && parent.getChildPosition(view) == 1))
outRect.top = space;
}
在活动中:
recyclerView.addItemdecoration(new SpacesItemdecoration(20));
我试图使用view.getX(),它总是返回0.
有人可以帮我吗非常感谢!
解决方法
在您的情况下,您可以将两个边距设置为RecyclerView.但在我的情况下,图像与RecyclerView中的屏幕宽度匹配,我使用Itemdecoration来解决问题.
class ViewItemdecoration extends RecyclerView.Itemdecoration {
public ViewItemdecoration() {
}
@Override
public void getItemOffsets(Rect outRect,final View view,final RecyclerView parent,RecyclerView.State state) {
super.getItemOffsets(outRect,view,parent,state);
int position = parent.getChildAdapterPosition(view);
int spanIndex = ((StaggeredGridLayoutManager.LayoutParams) view.getLayoutParams()).getSpanIndex();
int type = adapter.getItemViewType(position);
switch(type){
case YOUR_ITEMS:
if (spanIndex == 0) {
outRect.left = 10;
outRect.right = 5;
} else {//if you just have 2 span . Or you can use (staggeredGridLayoutManager.getSpanCount()-1) as last span
outRect.left = 5;
outRect.right = 10;
}
}
}
}