Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 418
Zsombor Erdődy-Nagy Avatar asked May 23 '11 19:05

Zsombor Erdődy-Nagy


People also ask

How do you find current active fragments?

To get the current fragment that's active in your Android Activity class, you need to use the supportFragmentManager object. The supportFragmentManager has findFragmentById() and findFragmentByTag() methods that you can use to get a fragment instance.

How many fragments can there be in one activity?

Two Fragments should never communicate directly. Show activity on this post. There is no official guideline regarding the limit of fragments that can be added to an activity. You can have as many as you need and looks logical for your app.

How do I show fragments in activity XML?

You can add your fragment to the activity's view hierarchy either by defining the fragment in your activity's layout file or by defining a fragment container in your activity's layout file and then programmatically adding the fragment from within your activity.


1 Answers

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).

like image 74
didi_X8 Avatar answered Oct 02 '22 20:10

didi_X8