我如何提供很多碎片ViewPager和避免不良code? [英] How do I supply many Fragments to ViewPager and avoid bad code?

查看:106
本文介绍了我如何提供很多碎片ViewPager和避免不良code?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有20 FragmentActivity,他们都重新present喜欢与不同的力学游戏画面。 我希望把他们都在ViewPager。我想到的唯一的事情是这样的伪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();
        }
    }

 }

但应该有另一种方式来做到这一点。请问AP preciate任何帮助。

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

推荐答案

FragmentPagerAdapter 是足够聪明,没有实例化片段,他们需要每一次。所以你code是确定。这就是说,20个片段保存在内存中可能会有点吃不消。看看 FragmentStatePagerAdapter ,它会自动保存和恢复的片段,没有让他们住在内存中的所有的时间。

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);
}

这篇关于我如何提供很多碎片ViewPager和避免不良code?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆