26

I would like to scroll by a certain amount of pixels in y direction in my recyclerview. I know that there are methods like scrollToPosition() or scrollToPositionWithOffset(). However, those don't really fit my needs.

I saw that LayoutManager provides a method scrollVerticallyBy(int dy, RecyclerView.Recycler recycler, RecyclerView.State state). That sounds like what I want.

How do I use it? What are recycler and state? I didn't find any examples online, so some code would be useful.

user2426316
  • 7,131
  • 20
  • 52
  • 83

1 Answers1

16

I don't know about scrollVerticallyBy, that looks more like a internal method for the RecyclerView. Aren't you just looking for the methods scrollBy(int x, int y) and smoothScrollBy(int dx, int dy)?

From the documentation:

public void scrollBy (int x, int y)

Move the scrolled position of your view. This will cause a call to onScrollChanged(int, int, int, int) and the view will be invalidated.

Parameters
x int: the amount of pixels to scroll by horizontally
y int: the amount of pixels to scroll by vertically

You can use the methods like so:

recyclerView.scrollBy(0, 50); //Scroll 50 pixels down
recyclerView.scrollBy(0, -50); //Scroll 50 pixels up

The same goes for smoothScrollBy.

Community
  • 1
  • 1
rubengees
  • 1,841
  • 2
  • 16
  • 31
  • Ruben is totally right, `scrollVerticallyBy` is a internal method that you override when you're building a custom LayoutManager. For more info about its use take a look [here](http://wiresareobsolete.com/2014/09/building-a-recyclerview-layoutmanager-part-1/) – Gaëtan Maisse Mar 23 '16 at 14:06
  • 11
    scrollBy(int x, int y) and smoothScrollBy(int dx, int dy) is not supported in RecyclerView so your suggestion will not work – Simon K. Gerges Mar 28 '16 at 10:53
  • 1
    What do you mean by "is not supported"? I used those methods in a project and they worked fine. – rubengees Mar 28 '16 at 10:56
  • recyclerView.scrollBy() is not optimum metod when large set on items and have to set initial scroll. recyclerView.getLayoutManager().scrollVerticalBy() is way faster – Duna Sep 13 '16 at 10:25
  • 1
    tested and doesn't work. the reason might be that is a method related to the view, not to the LayoutManager which should be the one in charge of that. – desgraci Jul 23 '17 at 19:05