How do you set the column spacing with a RecyclerView using a GridLayoutManager? Setting the margin/padding inside my layout has no effect.
相关问题
- How can I create this custom Bottom Navigation on
- Bottom Navigation View gets Shrink Down
- How to make that the snackbar action button be sho
- Listening to outgoing sms not working android
- How to create Circular view on android wear?
相关文章
- android开发 怎么把图片放入drawable的文件夹下
- android上如何获取/storage/emulated/下的文件列表
- androidStudio有个箭头不认识
- SQLite不能创建表
- Windows - Android SDK manager not listing any plat
- Animate Recycler View grid when number of columns
- Why is the app closing suddenly without showing an
- Android OverlayItem.setMarker(): Change the marker
There is only one easy solution, that you can remember and implement wherever needed. No bugs, no crazy calculations. Put margin to the card / item layout and put the same size as padding to the RecyclerView:
item_layout.xml
activity_layout.xml
For those who have problems with staggeredLayoutManager (like https://imgur.com/XVutH5u)
recyclerView's methods:
sometimes return -1 as index so we might face troubles setting itemDecor. My solution is to override deprecated ItemDecoration's method:
instead of the newbie:
like this:
Seems to work for me so far :)
Try this. It'll take care of equal spacing all around. Works both with List, Grid, and StaggeredGrid.
Edited
The updated code should handle most of the corner cases with spans, orientation, etc. Note that if using setSpanSizeLookup() with GridLayoutManager, setting setSpanIndexCacheEnabled() is recommended for performance reasons.
Note, it seems that with StaggeredGrid, there's seems to be a bug where the index of the children gets wacky and hard to track so the code below might not work very well with StaggeredGridLayoutManager.
Hope it helps.
thanks edwardaa's answer https://stackoverflow.com/a/30701422/2227031
Another point to note is that:
if total spacing and total itemWidth are not equal to the screen width, you also need to adjust itemWidth, for example, on adapter onBindViewHolder method
I ended up doing it like that for my RecyclerView with GridLayoutManager and HeaderView.
In the code below I set a 4dp space between every item(2dp around every single item and 2dp padding around the whole recyclerview).
layout.xml
fragment/activity
SpaceItemDecoration.java
Utils.java
This will work for
RecyclerView
with header as well.