How to scroll the RecyclerView programatically by a specific pixels?

最后都变了- 提交于 2019-12-07 10:29:45

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/39482009/how-to-scroll-the-recyclerview-programatically-by-a-specific-pixels

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!