Search code examples
androidandroid-fragmentsandroid-3.0-honeycomb

Is there a way to get references for all currently active fragments in an Activity?


I haven't found a simple way to get all currently active (visible, currently in Resumed state) Fragments in an Activity. Is it possible without custom bookkeeping in my Activity? It seems that the FragmentManager doesn't support this feature.


Solution

  • Looks like the API currently misses a method like "getFragments".
    However using the event "onAttachFragment" of class Activity it should be quite easy to do what you want. I would do something like:

    List<WeakReference<Fragment>> fragList = new ArrayList<WeakReference<Fragment>>();
    @Override
    public void onAttachFragment (Fragment fragment) {
        fragList.add(new WeakReference(fragment));
    }
    
    public List<Fragment> getActiveFragments() {
        ArrayList<Fragment> ret = new ArrayList<Fragment>();
        for(WeakReference<Fragment> ref : fragList) {
            Fragment f = ref.get();
            if(f != null) {
                if(f.isVisible()) {
                    ret.add(f);
                }
            }
        }
        return ret;
    }
    

    In case there's no ready method to read the state from the object (isActive() in the example), I would override onResume and onPause to set a flag (could be just a bool field).
    That's already some own bookkeeping, but still very limited in my opinion considering the quite specific goal you want to achieve (status dependent list).