如何使用Android Fragment?
我正在查看一些演示代码,展示如何使用片段适配器(在本例中为选项卡适配器)。我很好奇 instantiate()
方法到底是做什么的。我看到它在此页面上的以下演示代码中使用:
http: //developer.android.com/reference/android/support/v4/view/ViewPager.html
(请参阅 TabsAdapter
类中的 getItem()
方法)
如果我正确地阅读了演示代码,每次用户单击其中一个选项卡时,都会创建一个新的片段?因此片段再次开始整个生命周期(onAttach()
...onCreate()
...等)?这听起来效率极低。我认为代表每个选项卡内容的片段应该只实例化一次(可能在 addTab() 方法中),然后保存到某个集合中,当 >getItem()
被调用。
如果我在这方面有任何错误,请纠正我。我试图更好地理解如何管理片段。
I'm looking at some demo code that shows how to use a Fragment Adapter (Tab Adapter in this case). I'm curious as to what exactly the instantiate()
method does. I see it used in the following demo code on this page:
http://developer.android.com/reference/android/support/v4/view/ViewPager.html
(see the getItem()
method within the TabsAdapter
class)
If I'm reading the demo code correctly, every time a user clicks on one of the tabs, a new Fragment is created? And thus the fragment starts the entire life-cycle again (onAttach()
...onCreate()
... etc)? This sounds awfully inefficient. I would think that the fragment that will represent the content for each tab should be instantiated only once (perhaps in the addTab()
method), and then saved into some collection where it can be fetched when getItem()
is called.
Please correct me if I'm mistaken in any of this. I'm trying to better understand how to manage fragments.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我的钱是,setCurrentItem() 函数实际上不会破坏该选项卡中显示的现有片段。否则,适配器实际上没有太多理由拥有可用选项卡列表。很可能,当您从一个选项卡切换到另一个选项卡时,
setCurrentItem()
只是将 UI 与当前活动的 Fragment 分离(或调用其onPause()
方法),然后重新启动附加新选择的 Fragment 的 UI(或调用其onResume()
方法)。但是,如果您有疑问,您可以阅读来源:)
希望它有帮助,
大卫
My money would be on that the
setCurrentItem()
function doesn't actually destroy the existing Fragment being shown in that tab. Otherwise there's really not much of a reason for the adapter to have a List of available tabs. Likely, when you switch from one tab to another,setCurrentItem()
just detaches the UI from the currently active Fragment (or calls itsonPause()
method) and then re-attaches the UI for the newly selected Fragment (or calls itsonResume()
method).But, if you're in doubt, you could read the source :)
Hope it helps,
David
我可以在此处找到我的问题的解释
I was able to find an explanation for my question here