Android - RecyclerView spacing between items in a Grid

Ernestina Juan picture Ernestina Juan · Jul 18, 2015 · Viewed 45.3k times · Source

In my Android app I'm using a RecyclerView to display items in a grid by using a GridLayoutManager. In a GridView, in order to specify the spacing between elements, I would set the horizontalSpacing and verticalSpacing properties.

So, how can I do the same on a RecyclerView?

Answer

josemigallas picture josemigallas · Jun 30, 2016

I haven't tested it with a GridLayout but for a LinearLayout, I simply set a margin to each listitem's root layout. I guess if you want the same space between all items (let's say 8dp), you would have to do this:

  1. Set layout_padding 4 dp to the RecyclerView.
  2. Set layout_margin 4 dp to each listitem.

This way you would have a constant 8 dp around every item.


The code below is a horizontal RecyclerView that displays images with a correct spacing of 8 dp:

<!-- fragment_layout.xml -->
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="4dp">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layoutManager="android.support.v7.widget.LinearLayoutManager"
        tools:listitem="@layout/list_item" />

</LinearLayout>

<!-- list_item.xml -->
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" 
    android:layout_margin="4dp">

    <ImageView
        android:layout_width="@dimen/thumbnail_size"
        android:layout_height="@dimen/thumbnail_size"
        android:contentDescription="@string/image_content_desc" />

</LinearLayout>

EDIT: I realised that the item view need to have a parent ViewGroup, so I updated the snippet.