Summary of RecyclerView waterfall

Catalog

 

Problems encountered

Solution

Problems encountered

  1. item jumps, leave blank at the top, sliding carton
  2. item set spacing

Solution

Question 1

The key is to know the original width and height of the image, and then set the item height dynamically according to the original width and height ratio of the image.

The original width and height of the picture can be returned by the background or acquired by yourself. The most convenient thing is that the interface returns.

Self access can be realized through the API provided by glide, as follows

GlideApp.with(context)
        .asBitmap()
        .load(url)
        .into(new SimpleTarget<Bitmap>() {
            @Override
            public void onResourceReady(@NonNull Bitmap bitmap, @Nullable Transition<? super Bitmap> transition) {
                //The original width and height of the picture
                int width = bitmap.getWidth();
                int height = bitmap.getHeight();
            }
        });

Dynamically set the height of the item as follows

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);

Question 2

Pass

addItemDecoration(new SpaceItemDecoration(getContext(), 10))

To set the spacing between item s, an example is given, as follows

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);
    }
}

 

Added by disaster77 on Tue, 24 Dec 2019 17:11:53 +0200