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
?
In your source code, add ItemOffsetDecoration to your RecyclerView. Item offset value should be half size of the actual value you want to add as space between items. mRecyclerView. setLayoutManager(new GridLayoutManager(context, NUM_COLUMNS); ItemOffsetDecoration itemDecoration = new ItemOffsetDecoration(context, R.
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:
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.
you have to use a ItemDecorator
for that:
like this:
public class EqualSpaceItemDecoration extends RecyclerView.ItemDecoration {
private final int mSpaceHeight;
public EqualSpaceItemDecoration(int mSpaceHeight) {
this.mSpaceHeight = mSpaceHeight;
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent,
RecyclerView.State state) {
outRect.bottom = mSpaceHeight;
outRect.top = mSpaceHeight;
outRect.left = mSpaceHeight;
outRect.right = mSpaceHeight;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With