Search code examples
javaandroidandroid-layoutandroid-recyclerviewstaggered-gridview

StaggeredGridLayoutManager: Adding Margin makes the layout items pushed to the side


So, I'm working on a small project and I wanted to add StaggeredGridLayoutManagerto the file. While it works if I don't add an itemDecorator and no margin or padding in my layouts. As soon as I add margins it pushes the list to one side. I'm attaching a screenshot to clarify the issue.enter image description here



Here is my Code:

recyclerView.setHasFixedSize(true);
    StaggeredGridLayoutManager gridLayoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
    recyclerView.addItemDecoration(new EqualSpaceItemDecoration(8));
    recyclerView.setLayoutManager(gridLayoutManager);
    recyclerView.setAdapter(adapter);

And the Layout File for the item

<?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"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:orientation="vertical">
  <android.support.v7.widget.CardView
    android:id="@+id/wallpaper_item_card"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:cardBackgroundColor="@color/cardview_light_background"
    app:cardCornerRadius="4dp"
    app:cardElevation="4dp"
    app:cardPreventCornerOverlap="false">

    <ImageView
      android:id="@+id/wallpaper_item_image"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"/>

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

I've looked around for some time and am not able to find something that fixes the issues. Any help is appreciated. Thanks.


Solution

  • I don't know if you've already found the solution, but I'll leave the comment in case anyone else sees the question.

    I was able to solve this problem by doing the following:

    layoutManager.setGapStrategy(StaggeredGridLayoutManager.GAP_HANDLING_NONE);
    

    Example:

    StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);          
    layoutManager.setGapStrategy(StaggeredGridLayoutManager.GAP_HANDLING_NONE);
    RecyclerView recyclerView = findViewById(R.id.recyclerView);
    recyclerView.setLayoutManager(layoutManager);