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:
Activity:
@Override
public boolean dispatchTouchEvent(MotionEvent event)
{
// if(mComicViewerFragment != null)
// mComicViewerFragment.consumeEvent(event);
mScaleDetector.onTouchEvent(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);
}
else
{
mComicViewerFragment.scrollBy((int)(-mScreenSize.y * 0.10f));
Log.i(ComicApplication.TAG, "ComicViewerActivity.onTouchEvent : You are tapping the upper part : " + y);
}
}
return super.dispatchTouchEvent(event);
}
Fragment
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.
How scroll RecyclerView to bottom in android programmatically? You can use scrollToPosition() with the index of the last position. Based on the doc, " RecyclerView does not implement scrolling logic, rather forwards the call to scrollToPosition(int)".
To be able to scroll through a vertical list of items that is longer than the screen, you need to add a vertical scrollbar. Inside RecyclerView , add an android:scrollbars attribute set to vertical .
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With