• 关于RecyclerView的瀑布流 分割线左右间距问题


    记录一下开发遇到的RecyclerView 的 瀑布流 左右间距设置问题。

    在GridLayoutManager中 ,item的布局顺序为

    在这里插入图片描述
    在该布局中,他的index就是左右左右,position所对应的itemView就是准确的。即 左0,右1,左2,右3,以此类推…
    但是如果是瀑布流,则会是另外一种顺序
    在这里插入图片描述
    可以看出瀑布流的position是根据列的高度来加载下一个position在哪里。所以我们会看到,左0,右1 之后,2到右边了,那是因为

    第二列的高度小于第一列的高度,所以就加载到第二列,以此类推, 下面的高度可以说就是随机展示的,谁也不知道接下来要怎么判断分割线。
    我们可以通过StaggeredGridLayoutManager.LayoutParams 里的getSpanIndex()来判断,这个方法不管你高度怎样, 他都是左右左右开始排列的。

    /**
     * @param space 每个item的左右间距
     * @param spanCount 一行中 item的个数
     * */
    class CostomizeItemDecoration(val space:Int,val spanCount:Int) : RecyclerView.ItemDecoration() {
        override fun getItemOffsets(
            outRect: Rect,
            view: View,
            parent: RecyclerView,
            state: RecyclerView.State
        ) {
            super.getItemOffsets(outRect, view, parent, state)
            if (view.layoutParams is StaggeredGridLayoutManager.LayoutParams){
                staggerdGridLayout(view, outRect)
            }else if (view.layoutParams is GridLayoutManager.LayoutParams){
                gridLayout(parent, view, outRect)
            }
    
        }
    
        private fun gridLayout(
            parent: RecyclerView,
            view: View,
            outRect: Rect
        ) {
            if (parent.getChildLayoutPosition(view) % spanCount == 0) {
                outRect.left = space
                outRect.right = space / spanCount
            } else {
                outRect.left = space / spanCount
                outRect.right = space;
            }
        }
    
        private fun staggerdGridLayout(view: View, outRect: Rect) {
            val params = view.layoutParams as? StaggeredGridLayoutManager.LayoutParams
            if ((params?.spanIndex ?: 0) % spanCount == 0) {
                outRect.left = space
                outRect.right = space / spanCount
            } else {
                outRect.left = space / spanCount
                outRect.right = space
            }
        }
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46

    参考自:

    Recyclerview之瀑布流分割线左右间距均等问题

  • 相关阅读:
    java毕业设计第二课堂选课系统Mybatis+系统+数据库+调试部署
    六个讨厌 Tailwind CSS 的理由
    WebRTC源码分析 nack详解
    业务指标采集影响系统性能问题排查
    异常:java lang AbstractMethodError
    BeanUtils.copyProperties的用法
    代码格式化----逗号问题
    ElasticSearch - DSL查询文档语法,以及深度分页问题、解决方案
    bootstrap按钮
    git提交代码自动部署,git-runner
  • 原文地址:https://blog.csdn.net/weixin_44710164/article/details/134514592