Referencing Fragments inside ViewPager

前端 未结 2 574
梦谈多话
梦谈多话 2021-02-04 13:43

I have a problem with referencing my Fragments inside a ViewPager. I would like to do it because from my activity I\'d like to refresh a fragment at a specified position (e.g. c

2条回答
  •  故里飘歌
    2021-02-04 14:16

    Two things:

    1. Add the following line in your Activity's onCreate method (or wherever you initialize your ViewPager):

      mPager.setOffscreenPageLimit(NUM_ITEMS-1);
      

      This will keep the additional off-screen pages in memory (i.e. preventing them from being destroyed), even when they aren't currently being shown on the screen.

    2. You might consider implementing your HashMap so that it holds WeakReferences instead of the Fragments themselves. Note that this would require you to change your getFragment method as follows:

      WeakReference weakRef = mPageReferenceMap.get(position);
      return (weakRef != null) ? weakRef.get() : null;
      

      This has nothing to do with your problem... it's just something I noticed and thought I would bring to your attention. Keeping WeakReferences to your Fragments will allow you to leverage the garbage collector's ability to determine reachability for you, so you don't have to do it yourself.

提交回复
热议问题