I am using the following simple FragmentStatePagerAdapter
and I want to get a reference to one of the fragments, keeping in mind that they may have been destroyed.
public class MyStatePagerAdapter extends FragmentStatePagerAdapter {
private int count;
public MyStatePagerAdapter(FragmentManager fm, int count) {
super(fm);
this.count= count;
}
@Override
public Fragment getItem(int arg0) {
switch (arg0) {
case 0:
return MyFragment1.newInstance();
case 1:
return MyFragment2.newInstance();
default:
return null;
}
}
@Override
public int getCount() {
return count;
}
}
I saw this question, whose second answer says that if you call FragmentStatePagerAdapter.instatiateItem
and there is already a reference to the fragment, it will not call getItem()
again. I looked at the source code here and to my understanding this is indeed what happens.
However, I was wondering, can I do something like the following? It seems straightforward enough, but the fact that I haven't seen it being used anywhere makes me suspicious that something is really wrong that I just can't see.
So basically my question is: What would be the errors in using something like the following to access the fragment?
public class MyStatePagerAdapter extends FragmentStatePagerAdapter {
private int count;
private MyFragment1 myFragment1;
private MyFragment2 myFragment2;
public MyStatePagerAdapter(FragmentManager fm, int count) {
super(fm);
this.count= count;
}
@Override
public Fragment getItem(int arg0) {
switch (arg0) {
case 0:
if (myFragment1 == null) {
myFragment1 = MyFragment1.newInstance();
}
return myFragment1;
case 1:
if (myFragment2 == null) {
myFragment2 = MyFragment2.newInstance();
}
return myFragment2;
default:
return null;
}
}
@Override
public int getCount() {
return count;
}
}
And to get it, I would call getItem(position)
.