开发者

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 thi开发者_如何学Pythons 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜