一.设置setImageParams方式
mAdapter = new DiamondRingZoneAdapter(R.layout.item_diamondringzone_item, list);
mAdapter.setImageParams(Util.getImageParams(mContext, 3, 0.9, 8));
mRecyclerView.setAdapter(mAdapter);
/**
* 获取Image图片的宽高
*
* @param context
* @param count
* @param scale
* @param left
* @return
*/
public static RelativeLayout.LayoutParams getImageParams(Context context,
int count, double scale, int left) {
//获取当前显示的界面大小
DisplayMetrics dm = context.getResources().getDisplayMetrics();
int w = dm.widthPixels; //获取当前界面的宽度
int imageWidth = w / count;//得到屏幕宽度的一半
int imageHeight = (int) (imageWidth * scale);
// int imageHeight = w / count;
//定义好控件的属性即把屏幕宽度的一半设置成imageview的宽高。LinearLayout表示 iv_hot_item 外层布局
// LinearLayout.LayoutParams imageParams = new LinearLayout.LayoutParams(imageWidth, imageHeight);
RelativeLayout.LayoutParams imageParams = new RelativeLayout.LayoutParams(imageWidth, imageHeight);
imageParams.setMargins(DensityUtil.dp2px(context, left), 0, 0, 0);
imageParams.addRule(RelativeLayout.CENTER_HORIZONTAL);//添加水平居中
return imageParams;
}
在Adapter中设置ImageView的params
public void setImageParams(RelativeLayout.LayoutParams imageParams) {
this.mImageParams = imageParams;
}
if (null != mImageParams) {
imgView.setLayoutParams(mImageParams);
}
整体左右边距在RecyclerView布局中设置
二.设置RecyclerView addItemDecoration方式
mRecyclerView.setLayoutManager(new GridLayoutManager(mContext, 2));
//重点
mRecyclerView.addItemDecoration(new RecyclerItemDecoration(dp2px(30), dp2px(30),2));
if (null == mAdapter) {
mAdapter = new GuessYouLikeAdapter(R.layout.item_guessyoulike, youLikeList,mContext);
mRecyclerView.setAdapter(mAdapter);
}
public class RecyclerItemDecoration extends RecyclerView.ItemDecoration {
private int itemSpaceLeft;
private int itemSpaceCenter;
private int itemNum;
public RecyclerItemDecoration(int itemSpaceLeft, int itemSpaceCenter, int itemNum) {
this.itemSpaceLeft = itemSpaceLeft;
this.itemSpaceCenter = itemSpaceCenter;
this.itemNum = itemNum;
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
int position = parent.getChildAdapterPosition(view);
if (parent.getChildCount() > 0) {
if (position % itemNum == 0) { //最左边Item
outRect.left = itemSpaceLeft;
outRect.right = itemSpaceCenter / 2;
} else if (position % itemNum == itemNum - 1) { //最右边Item
outRect.left = itemSpaceCenter / 2;
outRect.right = itemSpaceLeft;
} else { //中间Item
outRect.left = itemSpaceCenter / 2;
outRect.right = itemSpaceCenter / 2;
}
}
}
}