简体   繁体   English

带有 SnapHelper 装饰的 RecyclerView

[英]RecyclerView with SnapHelper decoration

I have a case when I have a photo gallery implemented as RecyclerView with SnapHelper.我有一个案例,当我使用 SnapHelper 将照片库实现为 RecyclerView 时。 Some photos (those that take full screen width) are 'glued' together.一些照片(那些占据全屏宽度的照片)被“粘合”在一起。 I want to add some decoration to it so it white spaces in between items, but only when one starts scorlling otherwise I want a photo to take entire width.我想给它添加一些装饰,以便在项目之间留出空白,但只有当一个人开始滚动时,否则我想要一张照片占据整个宽度。 I've tried:我试过了:

Creating custom decoration, I've manage to draw my decorating drawable off the screen so it would show only on scroll, but when overriding onDraw() it was invisible - hidden under next photo, and when I overrode onDrawOver() the edge of next photo was under divider.创建自定义装饰,我已经设法将我的装饰绘制从屏幕上绘制出来,因此它只会在滚动时显示,但是当覆盖onDraw()它是不可见的 - 隐藏在下一张照片下,当我覆盖onDrawOver()下一张的边缘时照片在分隔线下。 I was playing with adding padding to photos, and resetting it on idle state of recycler, but then the photo was jumping a bit.我正在尝试为照片添加填充,并在回收器的空闲状态下将其重置,但随后照片有点跳动。

I was also thinking of adding 'dummy' item between every photo that would act like divider, and force recycler to scroll by two position every time, but it seems that there might be better solution.我还想在每张照片之间添加“虚拟”项目,就像分隔符一样,并强制回收器每次滚动两个位置,但似乎可能有更好的解决方案。

You're on the right track using an ItemDecoration, but the method you should override is getItemOffsets() instead of onDraw/onDrawOver.您使用 ItemDecoration 走在正确的轨道上,但您应该覆盖的方法是getItemOffsets()而不是 onDraw/onDrawOver。 It lets you add space around your items.它可以让您在物品周围增加空间。

class LinearHorizontalSpacingDecoration(@Px private val innerSpacing: Int) :
    RecyclerView.ItemDecoration() {

    override fun getItemOffsets(
        outRect: Rect,
        view: View,
        parent: RecyclerView,
        state: RecyclerView.State
    ) {
        super.getItemOffsets(outRect, view, parent, state)

        val itemPosition = parent.getChildAdapterPosition(view)

        outRect.left = if (itemPosition == 0) 0 else innerSpacing / 2
        outRect.right = if (itemPosition == state.itemCount - 1) 0 else innerSpacing / 2
    }
}

Result with a 16dp spacing: 16dp 间距的结果:

以固定间距过渡

I've written a Medium post describing a step-by-step implementation of this kind of carousels using RecyclerView and SnapHelper, if you need more details (for example: how to achieve the scale effect).如果您需要更多详细信息(例如:如何实现缩放效果),我已经写了一篇Medium 文章,描述了使用 RecyclerView 和 SnapHelper 逐步实现这种轮播。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM