使用GridLayoutManager实现RecyclerView中的项目

时间:2015-11-17 19:55:52

标签: android margin android-recyclerview centering gridlayoutmanager

我使用GridLayoutManager实现了RecyclerView。

根据数据集中的项目数量,spanCount介于1-4之间。项目宽度根据spanCount而变化。如果spancount为4或更高,则spanCount保留为4.

如果我有5个项目,则剩下1个项目(1行中有4个项目,剩下1个项目),位于屏幕左侧,单独排成一行。我希望它集中在一起。

我尝试以编程方式设置左侧项目的边距,并将recyclerView和各个项目包装在LinearLayouts中,并将重力设置为居中,以及设置recyclerView的重力。

示例项XML:

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="horizontal"

    >


    <RelativeLayout
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:layout_gravity="center"
        android:id="@+id/relative"
        /> 

</LinearLayout>

RecyclerView XML示例

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:gravity="center"
            android:orientation="horizontal"
            >
           <android.support.v7.widget.RecyclerView
            android:id="@+id/recycler"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"

            />

        </LinearLayout>

任何人都可以建议解决方案,或者给我一些工作材料。

提前致谢。

1 个答案:

答案 0 :(得分:9)

答案是,当您设置GridLayoutManager的spancount时,无论您尝试多大的每个项目,它都不会扩展到超出单个项目允许的尺寸。这个允许的尺寸框&#39;在项目中,框的大小由Recyclerview的总高度和宽度指定,相对于GridLayoutManager上设置的spancount。这也意味着您无法使用重力设置将项目推送到其外面的框中。

项目的框/单元格通常如下计算:如果recylerview的宽度为100dp,spancount为2,则每个项目框/单元格的宽度为:width / spanCount。在这种情况下,每个框的宽度为50dp(100dp / spanCountOf2)。

为了让一个项目占用整个100dp,然后在100dp的空间中居中,该项目必须占用2个spancounts,即如果宽度为100dp,spancount为2,则每个项目为分配宽度为50dp(2个可用spancount中的1个),要使项目占用整个100dp,您需要告诉gridLayoutManager X位置的项目占用2 spanCounts而不是1.一旦项目占用了全部宽度或您希望它占用的跨度,它可以在其新定义的框内居中或调整大小(框大小是回收器相对于其spancount的宽度/高度)。

要更改给定项占用的跨度数,请在GridLayoutManager上调用:setSpanSizeLookup()。然后在setSpanSizeLookup()方法的return语句中标识要更改spanSize的项的位置,返回您希望它使用的跨度数:

 gridlayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
                @Override
                public int getSpanSize(int position) {
                    if (position == 1) {
                        return 4; // the item in position now takes up 4 spans
                    }
                    return 1;
                }
            });
        }

通过更改项目的spanCount,您可以使用重力设置将项目置于行的中间,如果该项目占用每行的总spancount。

但是,您可能会发现必须在适配器中使用备用布局,以使项目居中。因此,您可能需要在设置不同的跨度计数之间进行混合和匹配,并通过recyclerAdapter中的getItemViewType()方法使用不同的布局。