GridLayoutManager每行具有不同的列数

moy*_*oyo 2 android gridlayoutmanager android-recyclerview

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

在此处输入图片说明

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

我试图重新组织项目列表,将它们按行列表分组,然后每行增加一个LinearLayout。效果不佳。

所以我被困住了,没有想法。任何帮助将非常感激

Vol*_*kiv 5

您可以使用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
        }
     }
});
Run Code Online (Sandbox Code Playgroud)

我在上面的代码示例中仅显示了可以更改项目大小。注意spanSize<= spanCount