I’m working with a FragmentStatePagerAdapter using this example.
The MyAdapter class is implemented as follows:
public static class MyAdapter extends FragmentStatePagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
}
@Override
public int getCount() {
return NUM_ITEMS;
}
@Override
public Fragment getItem(int position) {
return ArrayListFragment.newInstance(position);
}
}
The ListFragment class includes the following method to create a new instance:
/**
* Create a new instance of CountingFragment, providing "num"
* as an argument.
*/
static ArrayListFragment newInstance(int num) {
ArrayListFragment f = new ArrayListFragment();
// Supply num input as an argument.
Bundle args = new Bundle();
args.putInt("num", num);
f.setArguments(args);
return f;
}
When I create a new fragment state pager adapter in my activity, getItem is called, which in turn calls the newInstance method in the ListFragment class. This is great when I want to create a new fragment.
But it’s not clear to me how to modify getItem (if even needed) to get the fragment object when it already exists and the user pages from, for example, page 2 to page 1. I’d like my Activity to retrieve that existing, previously created fragment so that it can run an inner class AsyncMethod, which resides in the fragment class.
I have implemented something similar to what you have. I extended the
FragmentPagerAdapterclass like so:Notice I have added an argument to the constructor to pass in the
ListofFragmentobjects. This way thegetItem()method of this class can return any class that extendsFragmentor any of its subclasses and not just one specific classArrayListFragmentlike you have done.In the
Activitywhere I instantiate my subclass ofFragmentPagerAdapterI have passed in the list ofFragmentobjects:Class the instantiates the FragmentPagerAdapter
By accessing the variable “fragments”, you can access a previously created
Fragmentso that you can run methods of thatFragment.