如何以编程方式将RecyclerView滚动特定像素? [英] How to scroll the RecyclerView programatically by a specific pixels?

查看:154
本文介绍了如何以编程方式将RecyclerView滚动特定像素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我扩大了recyclerview的范围,因此可以进行缩放.它以我想要的方式工作,但现在我想以编程方式滚动x个像素.用户的故事是,如果我点击屏幕的上半部分,它应该滚动x像素量,同样会移到屏幕的下半部分.

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.

这就是我所做的:

活动:

@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);
}

片段

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

每次点击时,它都不会滚动x个像素.这是因为我创建了一个从RecyclerView扩展的自定义视图吗?我应该在哪里正确地调用smoothScrollBy?假设这很容易,但我被困住了.

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.

推荐答案

由于recyclerView.smoothScrollBy(0, pixels);不适用于您的自定义视图,因此您可以尝试另一种方法.

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.

假设地说,如果您的商品的高度等于100dp,则可以通过代码请参见此处

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

让我们说100dp等于每个项目100像素,而您想向下滚动400像素到回收站.那是4个职位(400/100).

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

然后您需要的是View底部项目位置编号中的当前编号,加4并按位置滚动或平滑滚动.

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

这篇关于如何以编程方式将RecyclerView滚动特定像素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆