Android viewpager同步滚动
我有两个 ViewPager——Pager1 和 Pager2。我向 Pager1 添加了一个 OnPageChangeListener,并在 onPageScrolled 回调中调用 Pager2.scrollTo(x, y) 来移动它。两个 ViewPager 都可以平滑滚动并且同步,但问题是 Pager2 的内容没有改变。我用 LogCat 检查了它——Pager2 的 instantiateItem() 根本没有被调用。
作为解决方法,我将 Pager2.setCurrentItem() 添加到 Pager1 的 onPageSelected() 回调中。虽然这确实会滚动两个视图,但它并不与像素同步。我想知道是否有一种方法可以实现这种效果,而不必重写实际的 ViewPager 类。
I have two ViewPagers -- Pager1 and Pager2. I added an OnPageChangeListener to Pager1 and in the onPageScrolled callback, I call Pager2.scrollTo(x, y) to move it. Both of the ViewPagers do scroll smoothly and are synchronized, but the problem is that the contents of Pager2 do not change. I checked it with LogCat -- instantiateItem() for Pager2 doesn't get called at all.
As a workaround, I added Pager2.setCurrentItem() to the onPageSelected() callback for Pager1. While this does scroll both Views, it's not synchronized to the pixel. I'm wondering if there's a way to achieve this effect without having to override the actual ViewPager class.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
最适合我的解决方案是在
ViewPager
实例之间的OnTouchListener
中传递MotionEvent
。尝试过假拖动,但它总是滞后且有问题 - 我需要一个平滑的、类似视差的效果。因此,我的解决方案是实现一个 View.OnTouchListener。必须缩放
MotionEvent
以补偿宽度差异。然后将其设置为您的
ViewPager
请注意,此解决方案仅在两个寻呼机具有相同方向时才有效。如果您需要它适用于不同的方向 - 调整
syncEvent
Y 坐标而不是 X 坐标。我们还需要考虑一个问题 - 可能导致只有一个寻呼机的最小滑动速度和距离更改页面。
通过向寻呼机添加
OnPageChangeListener
可以轻松修复此问题The solution that worked best for me was to pass
MotionEvent
inOnTouchListener
betweenViewPager
instances. Tried fake dragging but it was always laggy and buggy - I needed a smooth, parallax-like effect.So, my solution was to implement a
View.OnTouchListener
. TheMotionEvent
has to be scaled to compensate for the difference in width.Then set it to your
ViewPager
Note that this solution will only work if both pagers have the same orientation. If you need it to work for different orientations - adjust
syncEvent
Y coordinate instead of X.There is one more issue that we need to take into account - minimum fling speed and distance that can cause just one pager to change page.
It can be easily fixed by adding an
OnPageChangeListener
to our pager您尝试过
beginFakeDrag()
吗?Have you tried
beginFakeDrag()
?