如何向 ViewPager 提供许多 Fragments 并避免错误的代码?
我有 20 个 FragmentActivity,它们都代表具有不同机制的游戏屏幕。 我想把它们全部放在ViewPager中。我唯一想到的是这个虚拟代码:
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();
}
}
}
但应该有另一种方法来做到这一点。将不胜感激任何帮助。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
FragmentPagerAdapter
足够智能,无需在每次需要时都实例化片段。所以你的代码没问题。也就是说,内存中保存 20 个片段可能有点太多了。看看FragmentStatePagerAdapter
,它会自动保存和恢复片段,而不是一直将它们保留在内存中。您可以拥有一个片段列表并从列表中返回,而不是使用
switch
: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 atFragmentStatePagerAdapter
, 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:使用
FragmentStatePagerAdapter
而不是FragmentPagerAdapter
。FragmentStatePagerAdapter
使用ArrayList
来存储片段,而FragmentPagerAdapter
使用getFragmentByTag
。Use
FragmentStatePagerAdapter
instead ofFragmentPagerAdapter
.FragmentStatePagerAdapter
is usingArrayList
to store fragments, butFragmentPagerAdapter
is usinggetFragmentByTag
.说实话,我不认为这有什么问题,你在很多游戏中都会看到类似的情况,比如菜单、游戏、暂停、游戏结束等屏幕。
我想说的是,每次更改到不同的页面时,您是否确实需要创建一个“新”片段。
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.