GridView在行中具有不同的列宽

时间:2016-02-19 06:30:56

标签: android gridview

我有一个GridView,我需要在其中显示图像。我已应用以下逻辑:

If 1 Photo : 1 row and 1 col and full width image.
If 2 Photos : 1 row and 2 cols with equal width of both images (half of screen width)
If 3 photos: 2 rows. 1st row will be having 1 col (1 image with full width)
and 2nd row will be having 2 images with equal width (half of screen width)

If 4 or more photos : width will be half for each column.

我已经管理了其余的情况,唯一的问题是当我有3张照片时设置案例3。 我希望第2行中的1张全宽照片和第2行中的2张相等的半宽照片,但是我的代码在第1行中给出了2张相等宽度的照片,在第2行中给出了1张半宽照片。

我只需要使用Gridview,请告诉我是否可以使用Gridview。我已经问过这个问题,但没有得到任何回复。 如果您有任何想法,请帮助我。

非常感谢你。

我想拥有以下布局:

enter image description here

1 个答案:

答案 0 :(得分:7)

见下面的代码

我已经创建了演示并且工作正常

  rv = (RecyclerView) findViewById(R.id.rv);
        final MyAdapter adapter = new MyAdapter();
        rv.setAdapter(adapter);
        GridLayoutManager mLayoutManager = new GridLayoutManager(this, 2);
        rv.setLayoutManager(mLayoutManager);

        mLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                if (adapter.getItemCount() == 1) {
                    return 2;
                } else if (adapter.getItemCount() == 2) {
                    return 1;
                } else if (adapter.getItemCount() == 3) {
                    if (position == 0) {
                        return 2;
                    } else {
                        return 1;
                    }
                } else {

                    return 1;

                }


            }
        });
相关问题