Thursday, 10 July 2014

Slide ViewPager on button click

You have changed ViewPager's page by sliding it. You can also change page by click on next and previous button.

  1. Add two button so called NEXT and PREV in xml.
  2. Instantiate these buttons in your activity. And create a global counter as follow

    int globalPosition = 0;

  3. Now set next click listener. as follow

    // checking if pager can scroll or not
    boolean can = mPager.canScrollHorizontally(1);
    
    if(can)
    {
     mPager.setCurrentItem(++globalPosition,true);
    }
    
    

  4. Set previous button click listener

    boolean can = mPager.canScrollHorizontally(-1);
    if(can)
    {
     mPager.setCurrentItem(--globalPosition,true);
    }
    

  5. Dont forget to update globalPosition on ViewPager page sliding.

    mPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
     @Override
     public void onPageSelected(int position) {
      globalPosition = position;
     }
    });
    


No comments:

Post a Comment