简体   繁体   English

如何为ViewPager提供许多片段并避免错误代码?

[英]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. 我有20个FragmentActivity,它们都代表着机制不同的游戏画面。 I want to put them all in ViewPager. 我想将它们全部放在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. FragmentPagerAdapter非常聪明,无需在每次需要时都实例化片段。 So you code is OK. 这样您的代码就可以了。 That said, 20 fragments kept in memory might be a bit too much. 也就是说,保存在内存中的20个片段可能有点过多。 Have a look at FragmentStatePagerAdapter , it will save and restore fragments automatically, without keeping them live in memory all the time. 看一看FragmentStatePagerAdapter ,它将自动保存和还原片段,而无需一直将它们保留在内存中。

Instead of using a switch you can have a list of fragments and return from the list: 您可以使用片段列表并从列表中返回,而无需使用switch

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而不是FragmentPagerAdapter

FragmentStatePagerAdapter is using ArrayList to store fragments, but FragmentPagerAdapter is using getFragmentByTag . FragmentStatePagerAdapter使用ArrayList存储片段,但是FragmentPagerAdapter使用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. 我要说的是,每次更改到另一个页面时,是否实际上需要创建一个“新”片段。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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