7

I need to synchronize the two ViewPager together. The requirement is something like on scrolling the ViewPager-1 and the ViewPager-2 should also scroll by certain amount. The Image shown below will make you more clear with my question.

enter image description here

You can also help me with some tutorials link. Thanks.

Pradip Kharbuja
  • 3,442
  • 6
  • 29
  • 50
Nitin Bathija
  • 800
  • 3
  • 12
  • 24

2 Answers2

15

I think this is what you need:

        viewpager1.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                viewpager2.onTouchEvent(event);
                return false;
            }
        });

        viewpager2.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                viewpager1.onTouchEvent(event);
                return false;
            }
        });

I have a same problem, but first I try to use fakeDragBy method, which is dead end. (if you have more than two pages)

Szelk Baltazár
  • 363
  • 2
  • 9
  • very nice and effective solution. Thank you! – Pradip Kharbuja May 07 '14 at 16:32
  • 2
    Using this technique, I get a crash if you simultaneously touch both view pagers. I ended up using the approach here instead: https://stackoverflow.com/a/26513243/369480 – gnuf Oct 09 '15 at 14:39
  • I like this solution because it's making the `ViewPagerIndicator` more smooth with the two view pagers, but it has a bug when you use multi-touch as described in the previous comment which I couldn't do something to prevent, so I disabled the multi-touch by using `android:splitMotionEvents="false"` in the XML layout and it now works good! – Ahmed Hegazy Oct 16 '18 at 15:28
2

You can extend ViewPager in order to create a custom view and override onTouchEvent() in the following way:

        @Override
        public boolean onTouchEvent(MotionEvent event) {

          if(mDependentView != null){
            mDependentView.onTouchEvent(event);
          }
          return super.onTouchEvent(event);
        }

Also create a setter inside your custom class in order to set the dependentView

public void setDependentView(View view){
   mDependentView = view;
}

Then you should set the second viewpager as dependent view of the first viewpager in your activity.

k_shil
  • 2,108
  • 1
  • 20
  • 25