4

I am developing a Project in which I am using View Pager on one screen, It only has two pages.

On the first one i have a simple form with some widgets. On the second page I have listview with some products name and quantitys.

Is possible to change from the first page to second after selecting an specific option of a spinner placed in this first page (Frgament)?

I have read on similar questions that this method :

ViewPager.setCurrentItem(int index);

makes possible changing to an specific page, the thing is i don't know how to reference to this viewpager object that i declare on my activity host from my fragment.

Henry1988
  • 83
  • 1
  • 1
  • 8

1 Answers1

23

Though, I don't understand the scenario completely. From what I understood, this is a hack that'd work in this case.

In Activity:

public ViewPager getViewPager() {
   if (null == mViewPager) {
       mViewPager = (ViewPager) findViewById(R.id.view_pager_id)
   }
   return mViewPager;
}

In Fragment:

((YourActivitName)getActivity()).getViewPager().setCurrentItem(index);
Gaurav Arora
  • 1,805
  • 13
  • 13
  • 8
    Better write public void setCurrentPagerItem(int item) { pager.setCurrentItem(item); } in Activity. – Yaroslav Mytkalyk Feb 08 '13 at 16:26
  • Thank you so much, it worked. Also the solution provided by @DoctororDrive works fine. – Henry1988 Feb 08 '13 at 19:01
  • 2
    The solution by @DoctororDrive is more "correct" (notice the quotes) because you're not exposing the ViewPager directly, which belongs to the internal Activity's implementation. Of course Java allows you to do either and you will get people supporting either method. – Martin Marconcini Jul 08 '13 at 23:00