使StaggeredGridLayout包装内容

时间:2015-03-18 09:23:26

标签: android android-support-library android-recyclerview

我需要在线性布局中显示交错网格。

enter image description here

为此,我在StaggeredGridLayoutManager的{​​{1}}上使用了RecyclerView。问题是android.support.v7.widget不支持StaggeredGridLayoutManager

还有其他问题可以解决这个问题,但它们关注的是线性布局,而不是交错的网格:

据我了解,我可以派生wrap_content并实施StaggeredGridLayoutManager。有没有办法做到这一点,而不是自己重新计算孩子的位置和大小?查看StaggeredGridLayoutManager.java source时,我可以看到它使用onMeasure来估算滚动内容的大小。有没有办法重用它?

2 个答案:

答案 0 :(得分:2)

问题在于,当绘制RecyclerView时,它会在绘制下一个元素之前计算所有剩余的大小,并且在绘制其他元素之后不会重新计算,将它们留在屏幕之外。

这个问题有一个简单的解决办法:诀窍是首先绘制所有其他元素,然后将RecyclerView留到最后。使用相对布局并将RecyclerView放在XML布局文件的最后。由于使用相对布局,您可以将每个元素放在XML文件上独立于任何位置的位置,您将在RecyclerView之前绘制所有元素,这将使其计算准确的剩余空间,并且wrap_content将正常工作。

在RecyclerView下添加paginagion栏的示例:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp"
    tools:context=".MainActivity"
    >

    <LinearLayout
        android:id="@+id/pagination_btns"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_alignParentBottom="true"> //HERE YOU ALIGN THIS ELEMENT TO THE BOTTOM OF THE PARENT
        <Button
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:text="@string/previous_btn_label"/>
        <Space
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"/>
        <Button
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:text="@string/next_btn_label"/>
    </LinearLayout>

    <android.support.v7.widget.RecyclerView
        android:id="@+id/items_recycler_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:scrollbars="vertical"
        android:layout_above="@id/pagination_btns"/> //HERE YOU ALIGN THE RECYCLERVIEW ABOVE THE PAGINATION BAR 


</RelativeLayout>

答案 1 :(得分:1)

相关问题