本文介绍了GridLayoutManager每行具有不同的列数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to build a RecyclerView with a GridLayoutManager which has a variable column count per row, something like this:

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

The sum of the width of all items in the same row will always be the screen width.

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

I tried to re-organize the list of items, grouping them by list of rows, and then inflating a LinearLayout per row. It didn't work quite well.

因此,我陷入了沉思,没了主意.任何帮助将不胜感激

So I'm stuck and out of ideas. Any help would be really appreciated

推荐答案

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

You can use GridLayoutManager. To have different column count in row you have to override 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.

I code sample above I just show have you can change item size. Pay attention that spanSize <= spanCount.

这篇关于GridLayoutManager每行具有不同的列数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-03 20:24