2

I've been trying to figure this out on my own, but no chance.

What I need is the RecyclerView (horizontal scrolling) to always show 3 items. And whenever the user flings or scrolls left and right, it should snap to the next 3 items, if there are any more. I'm just looking for the simplest solution if there's any.

I have found Gallery solutions with a single item, but I need 3 items. I know it must be possible but I couldn't really figure out how. For one, the LayoutManager should calculate the item width to match it with the width of the device. And I guess I need to use a RecyclerView.OnScrollListener somehow.

Anyone can help me out here?

Lanbo
  • 15,118
  • 16
  • 70
  • 147

3 Answers3

7

With LinearSnapHelper, this is now very easy.

All you need to do is this:

SnapHelper helper = LinearSnapHelper();
helper.attachToRecyclerView(recyclerView);

It's that simple! Note that LinearSnapHelper was added in the Support Library starting from version 24.2.0.

razzledazzle
  • 6,900
  • 4
  • 26
  • 37
1

I had a similar use case and I got good results using the suggestions in this SO thread:

Snappy scrolling in RecyclerView

The upshot is: use a custom RecyclerView.OnScrollListener to detect when the scroll state changes to SCROLL_STATE_IDLE, at which point use a subclass of LayoutManager which implements getFixScrollPos() to compute and then scroll to the correct position, snapping in the process.

I was also able to use a styleable attribute to set the number of items in the row at design time. You may want to do this as well.

Community
  • 1
  • 1
Patrick Brennan
  • 2,688
  • 3
  • 20
  • 30
0

Am I right in assuming that each page of the gallery is a vertical list of 3 items?

Call getWidth() and getHeight() within your override of LayoutManager.onMeasure(Recycler, int, int, int) to get the actual size of the recycler. You can then use that in onLayoutChildren() to figure out how large the children should be.

As for scrolling to the next views, I'm not entirely sure. Maybe add a custom OnScrollListener to the RecyclerView like in RecyclerView horizontal snap in center?

Community
  • 1
  • 1
Cliabhach
  • 1,402
  • 2
  • 12
  • 19