GridLayoutManager每行具有不同的列数

时间:2017-03-06 15:53:09

标签: android android-recyclerview gridlayoutmanager

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

enter image description here

同一行中所有项目的宽度总和将始终为屏幕宽度。

我尝试重新组织项目列表,按行列表对它们进行分组,然后每行充气一次LinearLayout。它效果不好。

所以我被困在想法中。任何帮助都会非常感激

2 个答案:

答案 0 :(得分:3)

您可以使用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

答案 1 :(得分:0)

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

spanSizeLookup 的设置示例 GridLayoutManager

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()
}