简体   繁体   English

第一次显示时仅加载一次标签(片段),并将其保留以备后用

[英]Load tab (Fragment) only once when it is shown for the first time and retain it for later use

I am able to show Fragments as tabs using ViewPager . 我可以使用ViewPagerFragments显示为选项卡。

What I want to achieve is, 我想要实现的是

  1. The contents of a fragment should be loaded only when it is selected as the current tab. 仅当选择片段作为当前选项卡时,才应加载片段的内容。
  2. Once a tab is shown and is loaded, then whenever I come back to the same tab then it is retained, ie not loaded again. 显示并加载选项卡后,每当我回到相同的选项卡时,该选项卡都会保留,即不再加载。

I know to retain all tabs I can use the following, 我知道保留所有标签,可以使用以下标签,

viewPager.setOffscreenPageLimit(4); // 4 is total number of tabs

But when I do this, it loads all 4 tabs at the very beginning ie calls onCreateView of all 4 tabs in the beginning. 但是,当我这样做时, 它将在开始时加载所有4个选项卡,在开始时调用所有4个选项卡的onCreateView How can I make it load only when it is shown for the first time and then retain for later use. 我如何才能使其仅在首次显示时加载,然后保留以备后用。

PS This functionality exists in Twitter and Facebook Android apps. PS此功能存在于Twitter和Facebook Android应用程序中。

To retain the fragments make your view pager adapter extend FragmentPagerAdapter instead of FragmentStatePagerAdapter. 要保留片段,请使视图分页器适配器扩展FragmentPagerAdapter而不是FragmentStatePagerAdapter。 The fragments will be retained in memory, so there is no need to set the page limit. 片段将保留在内存中,因此无需设置页数限制。 To fire the things you have to load upon user visibility, just extend setUserVisibleHint as mentioned above. 要触发用户必须加载的内容,只需如上所述扩展setUserVisibleHint。

@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
    if (isVisibleToUser && myData == null) {
        loadData()
    }
}

The android fragments do provide below method android片段确实提供了以下方法

@Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
    }

This method gets called in when the fragments become visible on screen only. 当片段仅在屏幕上可见时,将调用此方法。 So whatever the code you are executing in onCreateView() can be managed in this method. 因此,无论您在onCreateView()中执行的代码如何,都可以使用此方法进行管理。

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

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