简体   繁体   中英

How do I supply many Fragments to ViewPager and avoid bad code?

I have 20 FragmentActivity, they all represent like the game screens with different mechanics. I want to put them all in ViewPager. The only thing that comes to mind is this dummy code:

 public static class MyAdapter extends FragmentPagerAdapter {


    @Override
    public Fragment getItem(int position) {
        switch(position){
          case 0:
            return new Fragment1();
          case 1:
            return new Fragment2();
          .........................
          another 20 case statements here
          .........................
          case 20:
            return new Fragment21();
        }
    }

 }

But there should be another way to do it. Will appreciate any help.

FragmentPagerAdapter is smart enough to no instantiate fragments every time they are needed. So you code is OK. That said, 20 fragments kept in memory might be a bit too much. Have a look at FragmentStatePagerAdapter , it will save and restore fragments automatically, without keeping them live in memory all the time.

Instead of using a switch you can have a list of fragments and return from the list:

List<Fragment> fragments;

public Fragment getItem(int pos) {
  return fragments.get(pos);
}

public void addFragment(Fragment f) {
  fragments.add(f);
}

Use FragmentStatePagerAdapter instead of FragmentPagerAdapter .

FragmentStatePagerAdapter is using ArrayList to store fragments, but FragmentPagerAdapter is using getFragmentByTag .

I don't think there's anything very wrong with that to be honest, you see that kinda thing in lots of games where you have like a Menu, Game, Pause, Game Over etc screens.

What I would say though is whether you actually need to create a 'new' Fragment each time you change to a different page.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM