Sreejith SP
Sreejith SP

Reputation: 171

View Pager Android - Change Item

I have the following viewpager adapter.

public class MyFragmentPagerAdapter extends FragmentPagerAdapter {

        /** Constructor of the class */
        public MyFragmentPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        /** This method will be invoked when a page is requested to create */
        @Override
        public Fragment getItem(int arg0) {
            switch (arg0) {
            case 0:
                return new CreateLeague();
            case 1:
                return new JoinLeague();
            case 2:
                return new LeagueList();
            default:
                return null;
            }
        }

        /** Returns the number of pages */
        @Override
        public int getCount() {
            return 3;
        }
    }

I have a button in first fragment (Here CreateLeague()) and on taping that button, I want to change the view pager item to third one. viewPager.setCurrentItem(2); But this is another fragment and I can't access the viewpager object there. Is there any right way to do this?

Upvotes: 1

Views: 194

Answers (2)

adboco
adboco

Reputation: 2870

You can define an interface in the Fragment class and implement it within the Activity. The fragment alerts the activity when the button is clicked and then activity changes the current item. It's explained here

Upvotes: 1

daimajia
daimajia

Reputation: 967

You can use BroadcastReceiver.

If you are not familiar with BroadcastReceiver, you can view this tutorial.

Upvotes: 1

Related Questions