版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Lamphogani/article/details/82867476
目录
遇到的问题
- item乱跳,顶部留白,滑动卡顿
- item设置间距
解决办法
问题1
关键在于知道图片的原始宽高,然后根据图片的原始宽高比动态的设置item的高度。
图片的原始宽高可以由后台返回,也可以自己获取,最方便的就是接口返回了。
自己获取可以通过glide提供的API来实现,如下
GlideApp.with(context)
.asBitmap()
.load(url)
.into(new SimpleTarget<Bitmap>() {
@Override
public void onResourceReady(@NonNull Bitmap bitmap, @Nullable Transition<? super Bitmap> transition) {
//图片的原始宽高
int width = bitmap.getWidth();
int height = bitmap.getHeight();
}
});
动态设置item的高度,如下
ImageView imageView = viewHolder.getView(R.id.iv_item_list);
ViewGroup.LayoutParams layoutParams = imageView.getLayoutParams();
int itemWidth = (ScreenUtils.getScreenWidth(mContext) - 10 * 4) / 2;
float scale = ((float) itemWidth) / item.getWidth();
int itemHeight = (int) (item.getHeight() * scale);
layoutParams.width = itemWidth;
layoutParams.height = itemHeight;
imageView.setLayoutParams(layoutParams);
问题2
通过
addItemDecoration(new SpaceItemDecoration(getContext(), 10))
设置item之间的间距,提过一个样例,如下
public class SpaceItemDecoration extends RecyclerView.ItemDecoration {
private int space;
public SpaceItemDecoration(Context context, int space) {
this.space = dip2px(context, space);
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
int position = parent.getChildAdapterPosition(view);
outRect.left = space;
outRect.right = space;
outRect.bottom = space;
if (position == 0 || position == 1) {
outRect.top = space;
}
}
private int dip2px(Context context, float dpValue) {
float density = context.getResources().getDisplayMetrics().density;
return (int) (dpValue * density + 0.5f);
}
}