简体   繁体   English

防止在Viewpager中重新创建片段

[英]Prevent fragment re-create in viewpager

I want to prevent fragment re-create in viewpager , in default way every time you navigate to a fragment in viewpager , android creates a new instance of that fragment. 我想防止片段在viewpager中重新创建,默认情况下,每次您导航到viewpager中的片段时,android都会创建该片段的新实例。 setOffscreenPageLimit(x) can fix this problem but i don't want to load more fragments in activity's onCreate. setOffscreenPageLimit(x)可以解决此问题,但我不想在活动的onCreate中加载更多片段。 Any idea to solve this problem and maintain fragment instance after select for next time? 是否有解决此问题并在下次选择后维护片段实例的想法?

There are two most used classes for View Pagers are: “查看寻呼机”有两种最常用的类:

and they look alike in many ways but not all. 它们在很多方面看起来很相似,但并非全部。

What you need is FragmentPagerAdapter 您需要的是FragmentPagerAdapter

This will keep the Fragment as you want and not being recreated each time as the following quote say from the official documentantion: 这将保留您想要的片段,而不是每次都被重新创建,如官方文献中的以下引述所示:

Implementation of PagerAdapter that represents each page as a Fragment that is persistently kept in the fragment manager as long as the user can return to the page. PagerAdapter的实现,它将每个页面表示为一个Fragment,只要用户可以返回到该页面,该片段就会永久保存在片段管理器中。

And also here in the same documentation: 同样在同一文档中:

The fragment of each page the user visits will be kept in memory... 用户访问的每个页面的片段将保留在内存中...

Although remember using this, memory will be your responsibility and you will have to manage memory of your Views check the number of pages you are having first if they are many, its not a nice idea to display 50 pages this way. 尽管记住要使用它,但是内存将是您的责任,并且您将必须管理视图的内存,如果有很多页面,则首先检查您拥有的页面数,以这种方式显示50页不是一个好主意。 Only may be less than 10 ( Tabs may be its the best choice ). 只能小于10( 选项卡可能是它的最佳选择 )。 You are good. 你很好。 Memory management is the only thing to take NOTE here as the documentation itself say: 内存管理是唯一需要注意的地方,因为文档本身说:

This can result in using a significant amount of memory since fragment instances can hold on to an arbitrary amount of state. 由于片段实例可以保持任意数量的状态,因此这可能导致使用大量内存。 For larger sets of pages, consider FragmentStatePagerAdapter . 对于较大的页面集,请考虑FragmentStatePagerAdapter

So change your adapter to FragmentPagerAdapter and your fragments will be kept in memory not recreated. 因此,将您的适配器更改为FragmentPagerAdapter ,您的片段将保留在内存中,而不会重新创建。

Try setting Fragment.setRetainInstance(true) . 尝试设置Fragment.setRetainInstance(true) If you use FragmentPagerAdapter, this will cause an existing fragment to 'live' and not get re-created. 如果您使用FragmentPagerAdapter,这将导致现有片段“处于活动状态”并且不会被重新创建。 It will to get detached and re-attached instead. 它将脱离并重新连接。

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

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