I have the following situation:
I have an Activity
that hosts a ViewPager
, and I have 4 Fragments
;
the ViewPager
at the beginning contains Fragment A,
when the user swipes on the ViewPager
Fragment B goes into the ViewPager
, then Fragment C and Fragment D ...etc...
Now as soon as the FragmentPagerAdapter
is instantiated at least 2 of the Fragments are created.
This poses 2 problem:
- Every
Fragment
needs to perform network calls, but I do not want to do unnecessary ones (I do not want to make network calls for Fragment B, if the user never swipes to Fragment B ); - similar to 1.), I need to show a
ProgessDialog
when a Fragment perform network calls, but I do not want to show dialogs from Fragment B if the user never goes to it...
Please what kind of pattern should I use in such a circumstance?
Activity
public class PagerActivity extends ActionBarActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.viewpager_layout);
ViewPager pager=(ViewPager)findViewById(R.id.pager);
TabPageIndicator tabs=(TabPageIndicator)findViewById(R.id.titles);
pager.setAdapter(buildAdapter());
tabs.setViewPager(pager);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
}
FragmentPagerAdapter
public class MyFragmentPagerAdapter extends FragmentPagerAdapter {
@Override
public int getCount() {
return (4);
}
@Override
public Fragment getItem(int position) {
if (position == 1) {
if (dashbardFragment == null)
dashbardFragment = DashBoardFragment.newInstance(position);
return dashbardFragment;
}
if (position == 0) {
if (listOfParticipantFragment == null)
listOfParticipantFragment = ListOfParicipantsFragment
.newInstance(position);
return listOfParticipantFragment;
}
}
1 Fragment
public class ListOfParicipantsFragment extends Fragment {
public static ListOfParicipantsFragment newInstance(int position) {
ListOfParicipantsFragment frag = new ListOfParicipantsFragment();
return (frag);
}
public static String getTitle(Context ctxt, int position) {
return myApplication.getContext().getResources().getString(R.string.list_of_participants_fragment_title);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View result = inflater.inflate(R.layout.guest_list_fragment_layout,
container, false);
return (result);
}