Android RecyclerView实现图片瀑布流

1.图片瀑布流现在几乎基本上是app比较常见的图片展示方式,此文简单介绍下RecyclerView + Glide结合实现图片瀑布流的效果的实现方法之一,先上效果:


760F07CA8D6D5AD10D623B34EA28F162.gif

2.具体实现如下:

// 1.设置LayoutManager
StaggeredGridLayoutManager manager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
manager.setGapStrategy(StaggeredGridLayoutManager.GAP_HANDLING_NONE);
recyclerView.setLayoutManager(manager);

// 2.添加ItemDecoration
// 每个item之间的间距
int divider = DimenUtil.Dp2Px(8);
RecyclerView.ItemDecoration gridItemDecoration = new RecyclerView.ItemDecoration() {
        @Override
        public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, RecyclerView parent, @NonNull RecyclerView.State state) {
            StaggeredGridLayoutManager.LayoutParams layoutParams = (StaggeredGridLayoutManager.LayoutParams) view.getLayoutParams();
                int spanIndex = layoutParams.getSpanIndex();
                int position = parent.getChildAdapterPosition(view);
                outRect.bottom = divider;
                if (position == 0 || position == 1) {
                    outRect.top = divider * 2;
                } else {
                    outRect.top = 0;
                }
                if (spanIndex % 2 == 0) {//偶数项
                    outRect.left = divider;
                    outRect.right = divider / 2;
                } else {
                    outRect.left = divider / 2;
                    outRect.right = divider;
                }
        }
    };
recyclerView.addItemDecoration(gridItemDecoration);

// 3.设置RecyclerView的适配器Adapter,就是一个ImageView,就不详细补充adapter了。
// 此处主要写一下Glide加载圆角图片:
int radius = 10;// 圆角半径
RequestOptions options = new RequestOptions()
                .placeholder(defRes)
                .transform(new CenterCrop(), new GlideRoundTransform(radius))
                .diskCacheStrategy(DiskCacheStrategy.RESOURCE);
        Glide.with(context)
                .load(imgResource)
                .transition(DrawableTransitionOptions.withCrossFade())
                .apply(options)
                .into(imageView);

3.最后注意:瀑布流中的图片高度不一,不是固定的,图片是按照原始宽高比显示,所以图片的width和height最好由服务器接口返回即可(至于图片宽高的值:1.可通过最初的上传接口,告知服务器;2.也可上传到服务器以后,由服务器计算获取其宽高存入数据库);app拿到宽高设置到imageView即可。

你可能感兴趣的:(Android RecyclerView实现图片瀑布流)