Question

I'm writing an application that uses the FragmentPagerAdapter. The fragments in the adapter need to be updated according to outside data - but that doesn't happen. I noticed that the fragment classes are only instantiated once, in the getItem function:

@Override
public Fragment getItem(int position) {
    TabInfo info = mTabs.get(position);
    return Fragment.instantiate(mContext, info.clss.getName(),
                info.args);
}

Even if I delete the class and use a new one, nothing helps - this method is only called once, the first time that the tab is populated, and then never again. Anyone has an idea why?

Thanks!

Was it helpful?

Solution

getItem will be called whenever the adapter needs a fragment and the fragment does not exist.

If the fragment already exists in the FragmentManager then there is no need to instantiate it and getItem does not need to be called.

To update an existing fragment you would need to retrieve it from the FragmentManager or the adapter and manipulate it accordingly.

By default, the viewpager will create fragments for the visible page and the one next to it. I.e to start with, fragments in position 1 and 2. When you swipe to page 2, the fragment at position 3 will be created etc

OTHER TIPS

To be more specific than the answer above (which is correct!), getItem is called by FragmentPagerAdapter's instantiateItem(ViewGroup container, int position) method. Just in case that helps :)

Simply use FragmentStatePagerAdapter instead of FragmentPagerAdapter

FragmentStatePagerAdapter destroys the instance of unneeded instance of fragments and instantiates again on-demand basis. On the other hand, FragmentPagerAdapter just detach the Fragment and reattach it. So fragments created in FragmentPagerAdapter never get destroyed. That's why I always prefer FragmentStatePagerAdapter.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top