RecycleView设置item上下间距

时间:2021-07-03 10:53:32

使用方式:

RecyclerView rvParentCategory = (RecyclerView) view.findViewById(R.id.rv_parent_category);
rvParentCategory.addItemDecoration(new SpaceItemDecoration(DensityUtils.dp2px(getActivity(),20)));

自定义间距类:

package com.onetoo.www.onetoo.config;

import android.graphics.Rect;
import android.support.v7.widget.RecyclerView;
import android.view.View;

/**
* Created by longShun on 2017/2/7.
* desc
*/

public class SpaceItemDecoration extends RecyclerView.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) != -1)
outRect.top = space;
}
}

工具类

package com.onetoo.www.onetoo.utils;

import android.content.Context;
import android.util.TypedValue;

/**
* Created by longShun on 2016/10/20.
*
*/

public class DensityUtils {
private DensityUtils() {
}

/**
* dp转px
*/

public static int dp2px(Context context, float dpVal) {
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
dpVal, context.getResources().getDisplayMetrics());
}

/**
* sp转px
*/

public static int sp2px(Context context, float spVal) {
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,
spVal, context.getResources().getDisplayMetrics());
}

/**
* px转dp
*/

public static float px2dp(Context context, float pxVal) {
final float scale = context.getResources().getDisplayMetrics().density;
return (pxVal / scale);
}

/**
* px转sp
*/

public static float px2sp(Context context, float pxVal) {
return (pxVal / context.getResources().getDisplayMetrics().scaledDensity);
}
}