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.
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.
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.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With