设置LinearLayoutManager间距 1、继承RecyclerView.ItemDecoration,实现getItemOffsets方法
public class LinearSpacingItemDecoration extends RecyclerView.ItemDecoration { ? ? ? private int spacing;//间距padding ? ? ? public LinearSpacingItemDecoration(Context context, int spacings) { ? ? ? ? //获取需要设置的间距值dp,这里不写死,调用时传过来 // ? ? ? ?spacing = context.getResources().getDimensionPixelSize(R.dimen.d10); ? ? ? ? spacing = spacings; ? ? } ? ? ? @Override ? ? public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) { ? ? ? ? super.getItemOffsets(outRect, view, parent, state); // ? ? ? ?outRect.top = spacing;//item上边的间距 // ? ? ? ?outRect.left = spacing;//左边间距 // ? ? ? ?outRect.right = spacing;//右边间距 ? ? ? ? outRect.bottom = spacing;//设置bottom padding ? ? } } 2、然后在设置adapter之前添加上:
mRecyclerView.addItemDecoration(new LinearSpacingItemDecoration(spacings)); ?设置GridLayoutManager间距(网格布局): 1、和上边设置一样,继承RecyclerView.ItemDecoration,实现getItemOffsets方法
public class GridSpacingItemDecoration extends RecyclerView.ItemDecoration { ? ? private int spanCount; //列数 ? ? private int spacing; //间隔 ? ? private boolean isIncludeEdge; //是否有边缘 ? ? ? public GridSpacingItemDecoration(int spanCount, int spacing, boolean isIncludeEdge) { ? ? ? ? this.spanCount = spanCount; ? ? ? ? this.spacing = spacing; ? ? ? ? this.isIncludeEdge = isIncludeEdge; ? ? } ? ? ? @Override ? ? public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) { ? ? ? ? ? //判断你有几列,设置item ? ? ? ? int position = parent.getChildAdapterPosition(view); // item position ? ? ? ? int column = position % spanCount; // item column ? ? ? ? ? if (isIncludeEdge) { ? ? ? ? ? ? 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 ? ? ? ? ? ? } ? ? ? ? } ? ? } ? }
2、调用:
mRecyclerView.addItemDecoration(new GridSpacingItemDecoration(Count, spacing, isIncludeEdge)); 即可。 ?
|