onPageSelected isn’t triggered when calling setCurrentItem(0)

The cleanest solution I’ve found to this so far is to take a reference to the onPageChangeListener you set on the ViewPager (since I don’t think there’s a ViewPager.getOnPageChangeListener() method), then after you’ve set the ViewPager’s adapter, call:

onPageChangeListener.onPageSelected(viewPager.getCurrentItem());

However, the fragment for the page at the current index won’t have been instantiated yet (at least if you’re using FragmentStatePagerAdapter), so you may need to wrap it in a runnable, ala:

viewPager.post(new Runnable(){
@Override
    public void run() {
        onPageChangeListener.onPageSelected(viewPager.getCurrentItem());
    }
});

Also, if within the onPageSelected handler you need a reference to the fragment, you’ll have to do that yourself. I use an abstract base class for my FragmentStatePagerAdapter which overrides the instantiate and destroy methods, and adds/removes the fragments from a SparseArray.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)