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;  
        }  
    }



然后在使用RecyclerView的地方:

int spacingInPixels = getResources().getDimensionPixelSize(R.dimen.space);
 mRecyclerView.addItemDecoration(new SpaceItemDecoration(spacingInPixels));



Adapter填充上,再看看item就有间距了

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