0

I have an activity with 3 Fragments on a viewPager f1, f2, f3 displayed in 3 different tabs. What I would like achieve is below,

f3 visible -> user clicks on a button -> f2 has to be made visible
f2 visible -> user clicks on a button -> f1 has to be made visible

How can I achieve this?

dacscan3669
  • 651
  • 2
  • 8
  • 16

1 Answers1

2

The ViewPager method setCurrentItem(int) can make it.

@Override
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.SampleButton: {
            if (mViewPager.getCurrentItem() == 2) { // At f3
                mViewPager.setCurrentItem(1); // go to f2
            } else if (mViewPager.getCurrentItem() == 1) { // At f2
                mViewPager.setCurrentItem(0); // go to f1
            }
        }
        break;
    }
}

If you want really check the fragment is really visible to user, you need to override setUserVisibleHint on each Fragment. For that, please read this link; https://stackoverflow.com/a/9779971

Community
  • 1
  • 1
Youngjae
  • 24,352
  • 18
  • 113
  • 198