【问题标题】:GridLayoutManager with different column count per row每行具有不同列数的 GridLayoutManager
【发布时间】:2017-03-06 15:53:08
【问题描述】:

我正在尝试使用 GridLayoutManager 构建一个 RecyclerView,它的每行列数可变,如下所示:

同一行中所有项目的宽度之和总是屏幕宽度。

我尝试重新组织项目列表,按行列表对它们进行分组,然后为每行添加一个 LinearLayout。效果不太好。

所以我陷入困境并且没有想法。任何帮助将不胜感激

【问题讨论】:

    标签: android android-recyclerview gridlayoutmanager


    【解决方案1】:

    您可以使用 GridLayoutManager。要在行中有不同的列数,您必须覆盖 setSpanSizeLookup

    例子:

    //spanCount = 3 (just for example)
    GridLayoutManager gridLayoutManager = new GridLayoutManager(getAppContext(), spanCount);
    gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
        @Override
        public int getSpanSize(int position) {
            //define span size for this position
            //some example for your first three items
            if(position == item1) {
                return 1; //item will take 1/3 space of row
            } else if(position == item2) {
                return 2; //you will have 2/3 space of row
            } else if(position == item3) {
                return 3; //you will have full row size item
            }
         }
    });
    

    我上面的代码示例只是显示你可以更改项目大小。注意spanSize spanCount。

    【讨论】:

    • 问题是 spanCount 是每行可变的,但无论如何谢谢!我最终使用 12 作为 spanCount 并进行了一些计算来调整宽度。使用 12,它可以正常工作,每行 1、2、3 和 4 个元素。例如不是 5,但这不是常见的情况
    • @moyo 是的,你必须以任何方式进行一些计算:)
    【解决方案2】:

    我也有类似的情况,认为使用 kotlin 是个不错的选择:sealed class。您可以为适配器列表中的每个项目设置任何spanSizeLookup

    spanSizeLookupGridLayoutManager 的设置示例:

    val spanCount = 2
    val layoutManager =  GridLayoutManager(context, spanCount)
    layoutManager.spanSizeLookup = object : SpanSizeLookup() {
        override fun getSpanSize(position: Int): Int {
            val item = adapter.getItemList().getOrNull(position) ?: return spanCount
            return when (item) {
                is ProfileItem.Header -> spanCount
                is ProfileItem.Status -> spanCount
                is ProfileItem.Progress -> spanCount
                is ProfileItem.Empty -> spanCount
                is ProfileItem.Item -> spanCount / 2
                is ProfileItem.Load -> spanCount / 2
            }
        }
    }
    

    我的sealed class

    sealed class ProfileItem {
        object Header : ProfileItem()
        data class Status(var content: UserItem.User?) : ProfileItem()
        object Progress : ProfileItem()
        object Empty : ProfileItem()
        data class Item(val content: RecordItem.Record) : ProfileItem()
        object Load : ProfileItem()
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-05-08
      • 1970-01-01
      • 1970-01-01
      • 2015-08-04
      • 2015-07-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-28
      相关资源
      最近更新 更多