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.
7 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).
-
2Hmm, does the WeakReference
ref turn null if there's no references to the actual Fragment that was added to the list in onAttachFragment? – Jon Willis Aug 11 '11 at 22:23 -
2This works great for my purposes. PS I have the line: if (f != null && f.isVisible()) { ret.add(f); } – Jon Willis Aug 12 '11 at 02:13
-
No, ref itself will not turn null, only get() will return null if the activity was garbage collected. Thus assigning get() to a variable f and then check it for null is safe. – didi_X8 Aug 13 '11 at 03:03
-
Loved the solution greatGoing – B. TIger Jun 27 '13 at 23:39
-
As a similar solution I passed through `Fragment`'s `onAttach` and `onDetach` events to `FragmentActivity` via an extended callback interface (usually used for sending notifications about item selection in fragment). The methods add fragments to and then remove them from the internal list. It seems working without a need to use `WeakReference`s. – Stan Oct 30 '13 at 20:31
-
3Actually, the support library exposes a `getFragments()` method but it should not be used. It is marked with `@hide` and was not supposed to be included with the support library jar. It should not be considered part of the exported API. – James Wald Mar 25 '14 at 06:43
-
And how do you make that works for Fragments containing sub Fragments ? – Snicolas Jun 19 '14 at 18:28
-
Btw, looking at the android code, it looks like this will only give first level fragments, not nested fragments. – Snicolas Jun 19 '14 at 20:52
-
8Shouldn't the list of fragment references be updated, if a fragment is detached? Otherwise you might have Fragments in that list, which are already long gone (or at least not on screen anymore). – AgentKnopf Nov 10 '14 at 15:16
-
I'm using Navigation to change fragments, onAttachFragment is called only when the first fragment loads, never more. – sgm Jan 23 '21 at 23:01
-
Make sure to clean up this list. Else there will be memory leaks. Coming from first hand experience. AgentKnopf is correct. The list should get updated. – wseme Feb 02 '21 at 15:39
If you use Android Support Library, then you can call hidden FragmentManager.getFragments()
method:
public List<Fragment> getVisibleFragments() {
List<Fragment> allFragments = getSupportFragmentManager().getFragments();
if (allFragments == null || allFragments.isEmpty()) {
return Collections.emptyList();
}
List<Fragment> visibleFragments = new ArrayList<Fragment>();
for (Fragment fragment : allFragments) {
if (fragment.isVisible()) {
visibleFragments.add(fragment);
}
}
return visibleFragments;
}

- 53,859
- 22
- 133
- 139
-
1We shouldn't use this method. It is marked with `@hide` and was not supposed to be included with the support library jar. It should not be considered part of the exported API. – James Wald Mar 25 '14 at 06:44
-
1If you're using the support library and know what's inside, you can call any methods you want. The worst thing that can happen is that after switching to a newer version of the library you'll get compilation errors. – Michael Mar 25 '14 at 09:10
-
9@Michael One important thing I'd like to note for this method for future viewers (which it looks like you've got covered here) is that it's returning the internal fragment list, and not a copy of it. So don't modify the list you get back; instantiate a new List based off of the returned response and modify *that* one. Otherwise you'll spend an entire day debugging an intermittent IndexOutOfBoundsException. :) – Kevin Coppock May 03 '14 at 01:11
-
Just want to point out as @Michael mentioned, the method has since been removed. – Jason Robinson Aug 17 '16 at 19:31
-
1From what I can see, the method is still visible, [but it has a bug](https://code.google.com/p/android/issues/detail?can=2&start=0&num=100&q=&colspec=ID%20Type%20Status%20Owner%20Summary%20Stars&groupby=&sort=-id&id=226196) – Al Lelopath Nov 16 '16 at 15:43
-
Since https://android.googlesource.com/platform/frameworks/support/+/android-7.1.1_r24/fragment/java/android/support/v4/app/FragmentManager.java#329 the method `getFragments` is restricted to libraries from the same groupId and Android Lint will throw a Lint error if you're using it. – Nahuel Barrios Mar 09 '17 at 21:37
-
Yes, that's true but I'm sure the Android team has a good reason to restrict that method usage so I think it's not a good decision ignoring that error. By the way the RestrictedApi is considered as an error by default with priority 4/10 (http://tools.android.com/tips/lint-checks) – Nahuel Barrios Mar 10 '17 at 13:58
Another way to do this would be to put tags on your fragments when you add them to the activity.
For example, if you dynamically add 4 fragments, you can add them like:
for (int i = 0; i < NUM_FRAGMENTS; i++){
MyFragment fragment = new Fragment(i);
fragmentTransaction.add(R.id.containerId, fragment, SOME_CUSTOM_PREFIX + i).commit()
}
Then, if you need to get all the fragments back later, you can do:
for (int i = 0; i < NUM_FRAGMENTS; i++) {
String tag = SOME_CUSTOM_PREFIX + i;
fragmentList.add((MyFragment) fragmentManager.findFragmentByTag(tag));
}

- 1,621
- 12
- 18
I resolved with this:
public ArrayList<Fragment> getAllFragments() {
ArrayList<Fragment> lista = new ArrayList<Fragment>();
for (Fragment fragment : getSupportFragmentManager().getFragments()) {
try {
fragment.getTag();
lista.add(fragment);
} catch (NullPointerException e) {
}
}
return lista;
}

- 552
- 5
- 10
-
I'm implementing something similar to this and I am getting a NPE whenever the activity is recreated and fragment.getTag() is called. Do you know why the fragment is null? – Clocker Nov 14 '14 at 15:11
-
android.support.v4.app.FragmentManager
has a method called getFragments()
which does exactly what you need, but it was never accessible. Suddenly, though, it is, but I'm not sure if that's intended because it's still marked as hidden.
/**
* Get a list of all fragments that have been added to the fragment manager.
*
* @return The list of all fragments or null if none.
* @hide
*/
public abstract List<Fragment> getFragments();
The regular android.app.FragmentManager
doesn't have this method at all, but if really needed, you can access the same object by getting the field mActive
via reflection (be careful there: starting with API 26, its type is a SparseArray
instead of List
). Use at own risk :)

- 5,786
- 6
- 31
- 55
-
1The method is public, but [it has a bug](https://code.google.com/p/android/issues/detail?can=2&start=0&num=100&q=&colspec=ID%20Type%20Status%20Owner%20Summary%20Stars&groupby=&sort=-id&id=226196) – Al Lelopath Nov 16 '16 at 15:44
-
-
Here is a recursive solution in Kotlin. Given the top-most fragments of an activity, returns all the descendant fragments.
fun recursiveGetFragments(parents: List<Fragment>): List<Fragment> {
val result = parents.toMutableList()
for(root in parents) {
if (root.isVisible) {
result.addAll(recursiveGetFragments(root.childFragmentManager.fragments))
}
}
return result
}
It is used as:
val fragmentList = recursiveGetFragments(supportFragmentManager.fragments)

- 116
- 2
- 7
we can use some irregular-but-legal method
ArrayList<Fragment> getActiveFragments() {
Fragment f;
final ArrayList<Fragment> fragments = new ArrayList<>();
int i = 0;
try {
while ((f = getFragmentManager().getFragment(new Intent().putExtra("anyvalue", i++).getExtras(), "anyvalue")) != null) {
fragments.add(f);
}
} catch (IllegalStateException ex) {
}
return fragments;
}

- 1,172
- 1
- 8
- 13