32

I cannot find out a way to add an outer margin to the GridView rows. I found the setHorizontalSpacing and setVerticalSpacing properties which add inner padding between the GridView rows, however it doesn't apply to the outer borders of the rows.

I'd like to have a result as it's featured on the Google Play store:

enter image description here

Thanks!

Diego Acosta
  • 1,737
  • 3
  • 16
  • 21
  • Did you try to simply add padding (or a margin) to the `GridView`? – MH. Jun 17 '13 at 00:50
  • as @MH you can add the `android:paddingLeft/Right` properties with the same value of `setVertical/HorizontalSpace`. The drawback is that this value is fixed, and if you set `android:stretchMode="spacingWidth"` the resizing will modify only the inner spacings. – Cavaz Jul 03 '13 at 12:56
  • Adding padding to the GridView works as expected. However when the items start to scroll the padding remains fixed - i.e. when one of the items is hanging off the top of the screen there is a a white (in my case) strip between the top of the screen and the item. It would look way better if the margin was on the item inside the GridView, but those margins don't appear to be respected. – Scott Roberts Sep 30 '13 at 19:57
  • The only way I found to do this, is either use a ListView and add logic to create rows that looks like grid items, or extending ViewGroup and create a layout that supports this. I've found this library that uses the second approach: https://github.com/thquinn/DraggableGridView – Diego Acosta Oct 04 '13 at 18:04

2 Answers2

95

You can use android:clipToPadding=false to add padding that doesn't stay when the items are scrolled. Like this

<GridView
    android:id="@+id/grid"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:horizontalSpacing="16dp"
    android:verticalSpacing="16dp"
    android:padding="16dp"
    android:clipToPadding="false" />

And if you want the scrollbar on the outside of the padding area, set android:scrollbarStyle="outsideOverlay" thanks @Karl!

Cameron Ketcham
  • 7,966
  • 2
  • 28
  • 27
  • 13
    Also use: android:scrollbarStyle="outsideOverlay". This puts the scrollbar in the padding area. Otherwise it will be before the padding. – Karl Nov 12 '13 at 13:34
  • 9
    This was **incredibly hard** to find and not very intuitive. Thanks :) – eliocs Mar 07 '14 at 15:19
  • Thanks. This is also useful for preventing the currently selected row to not be off screen due to TV overscanning. – Brian F Leighty Jan 26 '15 at 19:48
  • what if i don't want to use padding? because my HeaderGridView has a header and i want it to fit the screen width! – Muhammad Babar Dec 02 '15 at 12:32
0

If you want result like GooglePlay store, you can set setHorizontalSpacing and setVerticalSpacing and then set layout_margin to GridView.

iman mohadesi
  • 109
  • 1
  • 8