效果图:
以两张图为例,左、右边距12,上边距12,下边距0
代码实现:
@Override
public void onBindViewHolder(final GankIoDataBean.ResultBean object, final int position) {
/**
* 注意:DensityUtil.setViewMargin(itemView,true,5,3,5,0);
* 如果这样使用,则每个item的左右边距是不一样的,
* 这样item不能复用,所以下拉刷新成功后显示会闪一下
* 换成每个item设置上下左右边距是一样的话,系统就会复用,就消除了图片不能复用 闪跳的情况
*/
if (position % 2 == 0) {
DensityUtil.setViewMargin(itemView, false, 12, 6, 12, 0);
} else {
DensityUtil.setViewMargin(itemView, false, 6, 12, 12, 0);
}
}
utils.java
package com.xl.test.utils;
import android.view.View;
import android.view.ViewGroup;
import com.xl.test.app.CloudReaderApplication;
/**
* Created by Administrator on 2015/10/19.
*/
public class DensityUtil {
/**
* 根据手机的分辨率从 dp 的单位 转成为 px(像素)
*/
public static int dip2px(float dpValue) {
final float scale = CloudReaderApplication.getInstance().getResources().getDisplayMetrics().density;
return (int) (dpValue * scale + 0.5f);
}
/**
* 根据手机的分辨率从 px(像素) 的单位 转成为 dp
*/
public static int px2dip(float pxValue) {
final float scale = CloudReaderApplication.getInstance().getResources().getDisplayMetrics().density;
return (int) (pxValue / scale + 0.5f);
}
/**
* 设置某个View的margin
*
* @param view 需要设置的view
* @param isDp 需要设置的数值是否为DP
* @param left 左边距
* @param right 右边距
* @param top 上边距
* @param bottom 下边距
* @return
*/
public static ViewGroup.LayoutParams setViewMargin(View view, boolean isDp, int left, int right, int top, int bottom) {
if (view == null) {
return null;
}
int leftPx = left;
int rightPx = right;
int topPx = top;
int bottomPx = bottom;
ViewGroup.LayoutParams params = view.getLayoutParams();
ViewGroup.MarginLayoutParams marginParams = null;
//获取view的margin设置参数
if (params instanceof ViewGroup.MarginLayoutParams) {
marginParams = (ViewGroup.MarginLayoutParams) params;
} else {
//不存在时创建一个新的参数
marginParams = new ViewGroup.MarginLayoutParams(params);
}
//根据DP与PX转换计算值
if (isDp) {
leftPx = dip2px(left);
rightPx = dip2px(right);
topPx = dip2px(top);
bottomPx = dip2px(bottom);
}
//设置margin
marginParams.setMargins(leftPx, topPx, rightPx, bottomPx);
view.setLayoutParams(marginParams);
view.requestLayout();
return marginParams;
}
}