动态列表视图的Android ViewPager +片段 [英] Android ViewPager + Fragments with dynamic ListViews
问题描述
在我的应用我有标签的活动(比方说10片)。每个标签页包含片段
与的ListView
(在此ListView中显示的数据是从我的服务器动态加载)。我使用 ViewPager
来显示这些页面。我不希望保留在内存中的所有片段
,所以我决定用 FragmentStatePagerAdapter
(我的适配器类扩展这些类)。
-
让我们说第三个标签被选中。然后,当我去为例,第一个选项卡,
片段
这个标签应该从头开始(创建这很好,这是怎么FragmentStatePagerAdapter
作品),但无此片段STRONG>恢复previous状态(例如,的ListView
不应该被滚动到的位置保存当此片段
最后一次访问 - 现在它滚动)。
所以我的第一个问题是:我怎么能实现这样的行为?换句话说,我希望我的电源适配器没有恢复片段
状态,当从头开始创建。 -
再一次,假设第三个标签被选中。然后,当我去为例,第二个选项卡,
片段
这个标签应该还是在内存中(这很好,这是怎么FragmentStatePagerAdapter
作品),但在这种情况下,我想,以决定是否我的的ListView
数据应该(在某些条件下)进行更新。我怎样才能通知该片段
,它的选择?
有关#1,看看<一个href=\"http://speakman.net.nz/blog/2014/02/20/a-bug-in-and-a-fix-for-the-way-fragmentstatepageradapter-handles-fragment-restoration/\"相对=nofollow>这个的博客文章。他们谈论固定FragmentStatePagerAdpater处理的片段类指数的变化,这不正是你想要的情况。然而,它显示了详细的状态是如何保存/恢复,你应该能够找出如何prevent从那里。
有关#2,在持有ViewPager分片实施OnPageChangeListener。然后使用这以获得当前的片段时,它改变,所以你可以调用一些它公开的方法,告诉它来更新。
In my app I have activity with tabs (let's say 10 tabs). Each tab page contains Fragment
with ListView
(data displayed in this ListView is loaded dynamically from my server). I use ViewPager
to display these pages. I don't want to keep all the Fragments
in memory, so I decided to use FragmentStatePagerAdapter
(My adapter class extends these class).
Let's say 3rd tab is selected. Then, when I go for example to the first tab,
Fragment
for this tab should be created from scratch (that's fine, it's howFragmentStatePagerAdapter
works) but without restoring previous state of this fragment (e.g.,ListView
shouldn't be scrolled to the position saved when thisFragment
was last accessed - now it is scrolled). So my first question is: how can I achieve such a behaviour? In other words, I want my adapter not to restoreFragment
state, when it is created from scratch.Once again, let's say 3rd tab is selected. Then, when I go for example to the second tab,
Fragment
for this tab should be still in memory (that's fine, it's howFragmentStatePagerAdapter
works), but in this situation I want to decide if myListView
data should be updated (depending on some conditions). How can I notify thisFragment
that it's selected?
For #1, take a look at this blog post. They talk about fixing FragmentStatePagerAdpater to handle the case where the fragment class for an index changes, which isn't exactly what you want. However, it shows in detail how state is saved/restored and you should be able to figure out how to prevent it from there.
For #2, implement OnPageChangeListener in the Fragment that holds the ViewPager. Then use this to get the current fragment when it changes so you can call some public method on it, telling it to update.
这篇关于动态列表视图的Android ViewPager +片段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!