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
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
!