Android RecyclerView设置item间距

RecyclerView没有可以直接设置间距的属性,但可以用ItemDecoration来装饰一个item,所以继承重写ItemDecoration就可以实现间距了

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.getChildPosition(view) != 0)  
                outRect.top = space;  //竖直布局          //outRect.left = space; 水平的布局

        }  
    }然后在使用RecyclerView的地方:

int spacingInPixels = getResources().getDimensionPixelSize(R.dimen.lift);
 mRecyclerView.addItemDecoration(new SpaceItemDecoration(spacingInPixels));这样运行就可以看见效果了

你可能感兴趣的:(Android RecyclerView设置item间距)