【问题标题】:Making StaggeredGridLayout wrap content使 StaggeredGridLayout 包装内容
【发布时间】:2015-11-22 04:37:39
【问题描述】:

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

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

还有其他问题解决了这个问题,但它们涉及线性布局,而不是交错网格:

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

【问题讨论】:

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


    【解决方案1】:

    问题是RecyclerView在绘制的时候,在绘制下一个元素之前,会计算所有剩余的大小给自己,而在绘制完其他元素之后不重新计算,将它们留在屏幕之外。

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

    在 RecyclerView 下方添加分页栏的示例:

    <?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>
    

    【讨论】:

      【解决方案2】:

      【讨论】:

        猜你喜欢
        • 2010-12-31
        • 2019-12-06
        • 2012-08-28
        • 2021-07-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多