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

眉间皱痕 提交于 2020-08-20 11:46:05

问题


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.



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.


回答1:


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);



回答2:


In kotlin use:

viewManager.gapStrategy = StaggeredGridLayoutManager.GAP_HANDLING_NONE


来源:https://stackoverflow.com/questions/52289080/staggeredgridlayoutmanager-adding-margin-makes-the-layout-items-pushed-to-the-s

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!