【问题标题】:RecyclerView GridLayoutManager: Individual layout per item countRecyclerView GridLayoutManager:每个项目计数的单独布局
【发布时间】:2019-08-22 23:08:24
【问题描述】:

我的 GridLayoutManager 需要一些帮助。

如果我有一个项目,它应该在中间正常显示。
对于两个项目,它们应该彼此相邻。 Example with 2 Items 从三到四个项目,它应该像正方形一样显示。 Example with 3 Items Example with 4 Items

如果我是对的,这应该是 spanCount 2 的情况。但是对于 5 个项目(所以连续三个)是有问题的

从五个项目(及以上)中,每个项目应连续 3 个 Example with 5 Items 如果底行的项目也在中间就更好了



我希望有人可以帮助我并提前感谢

【问题讨论】:

    标签: java android android-recyclerview gridlayoutmanager


    【解决方案1】:

    您可以通过子类化GridLayoutManager 来动态设置跨度,如下所示:

    class CustomGridLayoutManager(context: Context) : GridLayoutManager(context, 2) {
    
        override fun onLayoutChildren(recycler: RecyclerView.Recycler?, state: RecyclerView.State?) {
            updateSpanCount()
            super.onLayoutChildren(recycler, state)
        }
    
        private fun updateSpanCount() {
            val colCount = if (childCount <= 4) {
                2
            } else {
                3
            }
            this.spanCount = colCount
        }
    }
    

    如果您想将元素放在最后一行的中心,通过GridLayoutManager 来实现会有点复杂。为此,您可能需要检查FlexboxLayout。它是 Google 自己制作的库,具有 HTML5/CSS 世界中常见的弹性盒模型。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-08-26
      • 2014-12-21
      • 1970-01-01
      • 1970-01-01
      • 2021-05-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多