Referencing Fragments inside ViewPager

前端 未结 2 572
梦谈多话
梦谈多话 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 WeakReference<Fragment>s instead of the Fragments themselves. Note that this would require you to change your getFragment method as follows:

      WeakReference<Fragment> 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.

    0 讨论(0)
  • 2021-02-04 14:22

    I managed to solve it. The trick was to make a reference list inside Activity, not PagerAdapter. It goes like this:

    List<WeakReference<EventListFragment>> fragList = new ArrayList<WeakReference<EventListFragment>>();
    
    @Override
    public void onAttachFragment (Fragment fragment) {
        Log.i(TAG, "onAttachFragment: "+fragment);
        if(fragment.getClass()==EventListFragment.class){
            fragList.add(new WeakReference<EventListFragment>((EventListFragment)fragment));
        }
    }
    public EventListFragment getFragmentByPosition(int position) {
    
        EventListFragment ret = null;
        for(WeakReference<EventListFragment> ref : fragList) {
            EventListFragment f = ref.get();
            if(f != null) {
                if(f.getPosition()==position){
                    ret = f;
                }
            } else { //delete from list
                fragList.remove(f);
            }
        }
        return ret;
    
    }
    

    Of course your fragment has to implement a getPosition() function, but I needed something like this anyway, so it wasn't a problem.

    Thanks Alex Lockwood for your suggestion with WeakReference!

    0 讨论(0)
提交回复
热议问题