How can I overlap items in RecyclerView? Like stacking cards.
Thanks in advance.
How can I overlap items in RecyclerView? Like stacking cards.
Thanks in advance.
You have to write your own LayoutManager or extends LinearLayoutManager
LinearLayoutManager
, actually you would need to modify most of the code at the end. I believe You can start with copying the whole source code as your own CardStackLayoutManager
, and try editing onLayoutChildren
–
Essie To overlap recyclerView rows, you can use this.
Add this class to your activity. You can customize the vertOverlap.
public class OverlapDecoration extends RecyclerView.ItemDecoration {
private final static int vertOverlap = -40;
@Override
public void getItemOffsets (Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
final int itemPosition = parent.getChildAdapterPosition(view);
if (itemPosition == 0) {
return; }
outRect.set(0, vertOverlap, 0, 0);
}
} `
After that add your decoration to recyclerView before setting its layout manager, and we are done.
mRecyclerView.addItemDecoration(new OverlapDecoration());
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
Thanks to the @MojoTosh https://mcmap.net/q/518843/-how-to-overlap-items-in-linearlayoutmanager-recyclerview-like-stacking-cards
if (itemPosition == 0
cause it is useless if you have padding/margin in recyclerview –
Crankpin You have to write your own LayoutManager or extends LinearLayoutManager
LinearLayoutManager
, actually you would need to modify most of the code at the end. I believe You can start with copying the whole source code as your own CardStackLayoutManager
, and try editing onLayoutChildren
–
Essie opsenes answer works great! But I added a percentage calculation instead of a fixed value so that it can work for multiple devices and screens.
class ItemDecorator() : RecyclerView.ItemDecoration() {
override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
val position = parent.getChildAdapterPosition(view)
if (position != 0) {
val widthOverlapPercentage = 0.25
val previousView = parent[position - 1]
val overlapWidth = previousView.width * widthOverlapPercentage
outRect.left = overlapWidth.toInt() * -1
}
}
}
My solution is based on a horizontal RecyclerView
, so if you want to implement Vertical, just switch previousView.width
with previousView.height
, and outRect.left
with outRect.top
.
You can also set the percentage of the overlapping where 0 is no overlap, and 1 is full overlap.
© 2022 - 2024 — McMap. All rights reserved.