安卓学习笔记-RecyclerView使用Glide加载网络图片瀑布流失效的情况以及item间距设置
作者:互联网
瀑布流失效问题
- RecycleView瀑布流用Glide加载网络图片会导致瀑布流失效,因为不知道网络加载的图片具体高度是多少;这时候我们可以手动设置图片高度,随机值,这样瀑布流就能正常使用了
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
ResultBeanData.ResultBean.HotInfoBean hotInfoBean = datas.get(position);
//设置图片的高度,这个值根据情况设置,后面180是图片高度
int mHeight = (int) (300+Math.random()*180);
//获取LayoutParams
ViewGroup.LayoutParams params = holder.iv_hot.getLayoutParams();
//将LayoutParams即图片的高度设置为我们上面写的高度
params.height = mHeight;
//将这个高度重新赋给图片
holder.iv_hot.setLayoutParams(params);
Glide.with(mContext).load(Constants.IMAGE_URL+hotInfoBean.getFigure())
.into(holder.iv_hot);
holder.tv_name.setText(hotInfoBean.getName());
holder.tv_price.setText(hotInfoBean.getCover_price());
}
解决后效果图
设置item项之间的间距
- 写一个类
- interval用于设置间距
class StaggeredDividerItemDecoration extends RecyclerView.ItemDecoration {
private Context context;
private int interval;
public StaggeredDividerItemDecoration(Context context, int interval) {
this.context = context;
this.interval = interval;
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
// int position = parent.getChildAdapterPosition(view);
StaggeredGridLayoutManager.LayoutParams params = (StaggeredGridLayoutManager.LayoutParams) view.getLayoutParams();
// 获取item在span中的下标
int spanIndex = params.getSpanIndex();
int interval = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
this.interval, context.getResources().getDisplayMetrics());
// 中间间隔
//放弃之前的方法。这里设置让左右一样列表左右切换导致中间距离出现问题
outRect.left = interval/2;
outRect.right =interval/2;
// 下方间隔
outRect.bottom = interval;
}
}
- 调用,这样就设置了每个项的左右间距13,上面间距13
-
recyclerView.addItemDecoration(new StaggeredDividerItemDecoration(mContext,13));
标签:Glide,int,安卓,interval,item,LayoutParams,params,context,holder 来源: https://blog.csdn.net/qq275467589/article/details/116863567