• 关于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之瀑布流分割线左右间距均等问题

  • 相关阅读:
    Prometheus-Prometheus安装及其配置
    Spring AOP 基于注解源码整理
    设计模式学习笔记(十三)组合模式及其在树形结构中的应用
    冰冰学习笔记:进程概念
    Flink CDC-SQL Server CDC配置及DataStream API实现代码...可实现监控采集一个数据库的多个表
    【iOS】导航栏的显隐与self.view.height
    记录一次Bitbucket鉴权的坑
    车道线检测-CLRNet-CVPR2022论文学习笔记
    gitlab--基础--5.3--CICD--gitlab-ci.yml关键字
    redisson springboot配置
  • 原文地址:https://blog.csdn.net/weixin_44710164/article/details/134514592