FragmentPagerAdapter getItem is not called
I am not able to reuse fragment in FragmentPagerAdapter.. Using destroyItem() method, It is deleting the fragment but still does not called getItem() again..There are just 2-3 Images so I am using FragmentPagerAdapter Instead of FragmentStatePagerAdapter..
public class ExamplePagerAdapter extends FragmentPagerAdapter {
ArrayList < String > urls;
int size = 0;
public ExamplePagerAdapter(FragmentManager fm, ArrayList < String > res) {
super(fm);
urls = res;
size = urls.size();
}
@Override
public int getCount() {
if (urls == null) {
return 0;
} else {
return size;
}
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
FragmentManager manager = ((Fragment) object).getFragmentManager();
FragmentTransaction trans = manager.beginTransaction();
trans.remove((Fragment) object);
trans.commit();
}
@Override
public Fragment getItem(int position) {
Fragment fragment = new FloorPlanFragment();
Bundle b = new Bundle();
b.putInt("p", position);
b.putString("image", urls.get(position));
Log.i("image", "" + urls.get(position));
fragment.setArguments(b);
return fragment;
}
}
And In FragmentActivity,
pager.setAdapter(new ExamplePagerAdapter(getSupportFragmentManager(), res2));
KISS Answer:
Simple use FragmentStatePagerAdapter instead of FragmentPagerAdapter.
I got the answer.. Firstly I thought to delete this question as I am doing a very silly mistake but this answer will help someone who is facing the same problem that Instead of FragmentPagerAdapter
, use FragmentStatePagerAdapter
.
As @BlackHatSamurai mentioned in the comment:
The reason this works is because
FragmentStatePagerAdapter
destroys as Fragments that aren't being used.FragmentPagerAdapter
does not.
Using a FragmentStatePagerAdapter
didn't fully fix my problem which was a similar issue where onCreateView
was not being called for child fragments in the view pager. I am actually nesting my FragmentPagerAdapter
inside of another Fragment
therefore the FragmentManager
was shared throughout all of them and thus retaining instances of the old fragments. The fix was to instead feed an instance of the getChildFragmentManager
to the constructor of the FragmentPagerAdapter
in my host fragment. Something like...
FragmentPagerAdapter adapter = new FragmentPagerAdapter(getChildFragmentManager());
The getChildFragmentManager()
method is accessible via a fragment and this worked for me because it returns a private FragmentManager
for that fragment specifically for situations in which nesting fragments is needed. I hope this helps someone who may be having the same problem I was!!
- Keep in mind however to use
getChildFragmentManager()
your minimum API version must be atleast17 (4.2)
, so this may throw a wrench in your gears. Of course, if you are using fragments from the support library v4 you should be okay.