问题描述
是否有可能有 2 个同时滚动的 ViewPagers,如果我开始滚动其中一个,另一个执行完全相同的滚动行为.或者我应该实现 ViewPager 以外的东西.
Is it possible to have 2 ViewPagers that simultaniously scroll together, if I start scrolling on one, the other does the exact same scrolling behaviour. Or should I implement somthing other than a ViewPager.
谢谢
推荐答案
最适合我的解决方案是在 OnTouchListener 中的 ViewPager<之间传递 MotionEvent/code> 实例.尝试过假拖动,但它总是很慢而且有问题(也尝试了这个线程的解决方案 - 没用) - 我需要一个平滑的、类似视差的效果.
The solution that worked best for me was to pass MotionEvent in OnTouchListener between ViewPager instances. Tried fake dragging but it was always laggy and buggy (tried the solution from this thread too - didn't work) - I needed a smooth, parallax-like effect.
所以,我的建议是实现一个View.OnTouchListener.MotionEvent 必须缩放以补偿宽度差异.
So, my advice is to implement a View.OnTouchListener. The MotionEvent has to be scaled to compensate for the difference in width.
public class SyncScrollOnTouchListener implements View.OnTouchListener {
private final View syncedView;
public SyncScrollOnTouchListener(@NonNull View syncedView) {
this.syncedView = syncedView;
}
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
MotionEvent syncEvent = MotionEvent.obtain(motionEvent);
float width1 = view.getWidth();
float width2 = syncedView.getWidth();
//sync motion of two view pagers by simulating a touch event
//offset by its X position, and scaled by width ratio
syncEvent.setLocation(syncedView.getX() + motionEvent.getX() * width2 / width1,
motionEvent.getY());
syncedView.onTouchEvent(syncEvent);
return false;
}
}
然后将其设置为您的 ViewPager
sourcePager.setOnTouchListener(new SyncScrollOnTouchListener(targetPager));
请注意,此解决方案仅在两个寻呼机具有相同方向时才有效.如果您需要它适用于不同的方向 - 调整 syncEvent Y 坐标而不是 X.
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.
通过向我们的寻呼机添加 OnPageChangeListener 可以轻松解决此问题
It can be easily fixed by adding an OnPageChangeListener to our pager
sourcePager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset,
int positionOffsetPixels) {
//no-op
}
@Override
public void onPageSelected(int position) {
targetPager.setCurrentItem(position, true);
}
@Override
public void onPageScrollStateChanged(int state) {
//no-op
}
});
这篇关于Android 2 ViewPagers 同时滚动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)