Android ViewPager Prev/Next Button

Yoda picture Yoda · Jun 1, 2012 · Viewed 69k times · Source

Okay, so I'm developing an Android app that utilises a ViewPager to display pages.

Within each page, I have a set of buttons to use for navigating between pages (in addition to the swiping between pages). These buttons are for "first page", "previous page", "next page" and "last page".

What I can't figure out how to do is engineer a mechanism to enable a page change on a button click.

Anyone have any ideas?

ETA: To better explain the setup, the buttons are declared within each page's layout, and are inflated with the rest of the layout within the PagerAdapter. My problem is that I can't reference the ViewPager from within the PagerAdapter. Or at least, I can't think of a way to do it.

Answer

sweggersen picture sweggersen · Nov 8, 2012

Button:

Button yourButton = (Button)findViewById(R.id.button1);
    yourButton.setOnClickListener(new OnClickListener() {

     @Override
           public void onClick(View view) {
               mViewPager.setCurrentItem(getItem(+1), true); //getItem(-1) for previous
           }
        });

Function:

private int getItem(int i) {
       return mViewPager.getCurrentItem() + i;
}

Hope this helps :)