1. 程式人生 > >RecyclerView 的 item 的間距

RecyclerView 的 item 的間距

RecyclerView沒有可以直接設定間距的屬性,但可以用ItemDecoration來裝飾一個item,所以繼承重寫ItemDecoration就可以實現間距了

public classSpaceItemDecorationextendsRecyclerView.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就有間距了