Search code examples
androidandroid-layoutandroid-recyclerviewstaggeredgridlayout

how can I center items in each row in recyclerview staggeredgridlayout?


There is few examples about recyclerview, I havent found any related solution, Ill be glad if someone helps me. I just want make my view looks as in the left part of the photo

The right view is what I've done and the left view is what I want to achieve

This is recyclerview in fragment

    <android.support.v7.widget.RecyclerView
    android:id="@+id/recyclerView"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1"
    android:layout_marginTop="15dp"
    android:scrollbars="vertical"
    />

This is single item xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:layout_margin="2dp">

<android.support.v7.widget.CardView
    android:id="@+id/card_view"
    android:layout_gravity="center"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    card_view:cardBackgroundColor="#16AFCA"
    card_view:cardCornerRadius="3dp"
    card_view:contentPaddingLeft="10dp"
    card_view:contentPaddingRight="10dp"
    card_view:contentPaddingBottom="5dp"
    card_view:contentPaddingTop="5dp">

    <TextView
        android:id="@+id/tag"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#ffffff"
        android:textAllCaps="true"
        android:text="#love"
        android:gravity="center"/>

</android.support.v7.widget.CardView>

</RelativeLayout>

This is java code

        recyclerView = (RecyclerView)     view.findViewById(R.id.recyclerView);
    recyclerView.setHasFixedSize(true);
    staggeredGridLayoutManager = new   StaggeredGridLayoutManager(3,StaggeredGridLayoutManager.VERTICAL);
    staggeredGridLayoutManager.setGapStrategy(StaggeredGridLayoutManager.GAP_HANDLING_NONE);
    recyclerView.setLayoutManager(staggeredGridLayoutManager);
    adapter = new StaggeredLayoutAdapter(getActivity(),tags);
    recyclerView.setAdapter(adapter);

Solution

  • The StaggeredGridLayout is meant for a Pinterest-type view where the columns are aligned and the rows are jagged. You want the opposite: rows aligned and columns jagged.

    You would be interested in the answers to this question: Does anyone know how to do flow layout using RecyclerView?