Referencing Fragments inside ViewPager

前端 未结 2 573
梦谈多话
梦谈多话 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:22

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

    List> fragList = new ArrayList>();
    
    @Override
    public void onAttachFragment (Fragment fragment) {
        Log.i(TAG, "onAttachFragment: "+fragment);
        if(fragment.getClass()==EventListFragment.class){
            fragList.add(new WeakReference((EventListFragment)fragment));
        }
    }
    public EventListFragment getFragmentByPosition(int position) {
    
        EventListFragment ret = null;
        for(WeakReference 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!

提交回复
热议问题