第一步:封装一个SpaceItemDecoration类
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) {
/* outRect.left = space;
outRect.right = space;*/
// System.out.println("position"+parent.getChildPosition(view));
// System.out.println("count"+parent.getChildCount());
// if(parent.getChildPosition(view) != parent.getChildCount() - 1)
// outRect.bottom = space;
//改成使用上面的间隔来设置 上下左右间距
if (parent.getChildPosition(view) != -1) {
outRect.top = space;
outRect.left = space;
outRect.right = space;
outRect.bottom = space;
}
}
}
第二步:获取手机屏幕宽度
private DisplayMetrics metrics;
WindowManager manager = MainActivity.this.getWindowManager();
metrics = new DisplayMetrics();
manager.getDefaultDisplay().getMetrics(metrics);
public int getScreenWidth() {
return metrics.widthPixels;
}
第三步:设置RecyclerView 并将数据传到适配器
第四步:适配器中处理
接收数据
第五步:
写一个自定义布局类,继承RelativeLayout类,再重写onMeasure方法即可:
public class MyLayout extends RelativeLayout {
public MyLayout (Context context, AttributeSet attrs,
int defStyle) {
super(context, attrs, defStyle);
}
public MyLayout (Context context, AttributeSet attrs) {
super(context, attrs);
}
public MyLayout (Context context) {
super(context);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(getDefaultSize(0, widthMeasureSpec),
getDefaultSize(0, heightMeasureSpec));
int childWidthSize = getMeasuredWidth();
// 高度和宽度一样
heightMeasureSpec = widthMeasureSpec = MeasureSpec.makeMeasureSpec(
childWidthSize, MeasureSpec.EXACTLY);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
然后用MyLayout作为元素布局的最外层元素即可。
布局文件中的item图片自适应
结束!