Neon Warge Neon Warge - 4 months ago 49
Android Question

How to scroll the RecyclerView programatically by a specific pixels?

I had extended recyclerview so i can scale it. It works the way I wanted it but now I wanted to programmatically scroll by x amount of pixels. The user story for this is that, if I tap on the upper half part of the screen, it should scroll by x amount of pixel, same goes to the lower half part of the screen.

Here's what I did:


public boolean dispatchTouchEvent(MotionEvent event)
// if(mComicViewerFragment != null)
// mComicViewerFragment.consumeEvent(event);


if(event.getAction() == MotionEvent.ACTION_DOWN)
int y = (int) event.getY();

if(y >= mScreenSize.y / 2)
mComicViewerFragment.scrollBy((int)(mScreenSize.y * 0.10f));
Log.i(ComicApplication.TAG, "ComicViewerActivity.onTouchEvent : You are tapping the lower part : " + y);
mComicViewerFragment.scrollBy((int)(-mScreenSize.y * 0.10f));
Log.i(ComicApplication.TAG, "ComicViewerActivity.onTouchEvent : You are tapping the upper part : " + y);

return super.dispatchTouchEvent(event);


public void scrollBy(int by)
mScalingRecyclerView.smoothScrollBy(0, by);

Every time I tap, it doesn't scroll by x amount of pixels. Is this because I created a custom view extending from RecyclerView? Where should I properly call smoothScrollBy? This is suppose to be easy but I am stuck.


As recyclerView.smoothScrollBy(0, pixels); is not working for your custom view you can try an alternative way.

What you can do is scroll by position by doing some Math but it wont be exact to the pixel.

Hypothetically speaking if your Items are of equal height of 100dp you can convert dp to pixels for any screen type by code see here

Lets say 100dp comes to 100px per item and you want to scroll 400px down the Recycler. That's 4 positions (400 / 100).

All you need then is the current in View bottom item position number, add 4 and scroll or smooth scroll by position.

Here is a helper class to show you how to get the Top or Bottom item position in View if you wish to go both up or down the Recycler.

For a complete Solution Check here