android recyclerview一行多个之间的间距
时间: 2024-03-08 09:49:34 浏览: 63
要设置 RecyclerView 中一行多个 item 之间的间距,可以通过自定义 ItemDecoration 实现。以下是示例代码:
```java
public class GridSpacingItemDecoration extends RecyclerView.ItemDecoration {
private int spanCount;
private int spacing;
private boolean includeEdge;
public GridSpacingItemDecoration(int spanCount, int spacing, boolean includeEdge) {
this.spanCount = spanCount;
this.spacing = spacing;
this.includeEdge = includeEdge;
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
int position = parent.getChildAdapterPosition(view); // item position
int column = position % spanCount; // item column
if (includeEdge) {
outRect.left = spacing - column * spacing / spanCount; // spacing - column * ((1f / spanCount) * spacing)
outRect.right = (column + 1) * spacing / spanCount; // (column + 1) * ((1f / spanCount) * spacing)
if (position < spanCount) { // top edge
outRect.top = spacing;
}
outRect.bottom = spacing; // item bottom
} else {
outRect.left = column * spacing / spanCount; // column * ((1f / spanCount) * spacing)
outRect.right = spacing - (column + 1) * spacing / spanCount; // spacing - (column + 1) * ((1f / spanCount) * spacing)
if (position >= spanCount) {
outRect.top = spacing; // item top
}
}
}
}
```
可以在创建 RecyclerView 时,通过以下代码设置间距:
```java
int spacing = getResources().getDimensionPixelSize(R.dimen.grid_spacing);
recyclerView.addItemDecoration(new GridSpacingItemDecoration(2, spacing, true));
```
其中,`R.dimen.grid_spacing` 是在 dimens.xml 中定义的间距值,例如:
```xml
<dimen name="grid_spacing">16dp</dimen>
```
这样,就可以设置 RecyclerView 中一行多个 item 之间的间距。
阅读全文