首先需要用到自定義一個間距的speace
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.right = space;
// Add top margin only for the first item to avoid double space between items
if(parent.getChildPosition(view) ==0)
? ? ? ? ? ? outRect.left = space;
? ? }
}
然后自定義好之后我們來設置到我們的recyclerView上碧查。
```
int space = UIUtils.dip2Px(15);
recyclerview.addItemDecoration(new SpacesItemDecoration(space));
此處附加UIUtils.dip2Px方法
public static int dip2Px(int dip){
float density = getResource().getDisplayMetrics().density;
int px = (int) ((float) dip * density +0.5F);
return px;
? ? }
到此我們就實現(xiàn)動態(tài)設置間隔了