java RecyclerView设置项目之间的间距 Posted 2021-05-08
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java RecyclerView设置项目之间的间距相关的知识,希望对你有一定的参考价值。
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="185dp"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="@color/transparent"
android:padding="10dp">
<RelativeLayout
android:layout_width="165dp"
android:layout_height="280dp"
android:background="@color/white"
android:orientation="vertical">
</RelativeLayout>
</LinearLayout>
比如在这个Item,外面包一层透明的LinearLayout,通过padding和margin来控制间距
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
}
}
}
}
调用的地方
int spanCount = 3; // 3 columns
int spacing = 50; // 50px
boolean includeEdge = false;
mRecyclerView.addItemDecoration(new GridSpacingItemDecoration(spanCount, spacing, includeEdge));
这是LinearLayoutManager设置Item间距的的一个辅助类
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.left = space;
outRect.right = space;
outRect.bottom = space;
// Add top margin only for the first item to avoid double space between items
if (parent.getChildPosition(view) == 0)
outRect.top = space;
}
}
设置item间距
int space = 8;
mRecyclerView.addItemDecoration(new SpacesItemDecoration(spacingInPixels));
以上是关于java RecyclerView设置项目之间的间距的主要内容,如果未能解决你的问题,请参考以下文章
java 在RecyclerView项目之间添加分隔符
删除 RecyclerView android中项目之间的间距
Android - 网格中项目之间的 RecyclerView 间距
为什么我的RecyclerView项目之间的空间不一样?
RecyclerView 上下左右四种间距的设置方法
RecyclerView 中项目之间的空间