Reputation: 244
How would you give a vertical offset to items in a horizontal RecyclerView based on their position on the screen? As the user scrolls left or right, I want the objects to rise as they approach the middle and to lower as they approach the ends/sides of the screen.
Here's a picture of the effect I'm going for. Blue indicates scrolling left and right. Red indicates vertical offset for each item based on their position on the screen. I'd like for them to rise and lower smoothly based on position as the user scrolls left or right.
Upvotes: 0
Views: 326
Reputation: 62189
You have to create your custom ItemDecoration
, which will look like something like this:
public class MyItemDecoration extends RecyclerView.ItemDecoration {
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
final int childCount = parent.getAdapter().getItemCount();
final int center = childCount >> 1;
final int currentPosition = parent.getChildAdapterPosition(view);
if (currentPosition < center) {
outRect.set(0, 0, 0, currentPosition * 10);
} else {
outRect.set(0, 0, 0, (childCount - currentPosition) * 10);
}
}
}
Usage:
recyclerView.addItemDecoration(new MyItemDecoration());
Result:
Upvotes: 1