It looks like it's possible to get all fragments of an Activity pretty easily. But how can I get all subfragments for a given fragment ?
This question is also related to getParentFragment API 16
It looks like it's possible to get all fragments of an Activity pretty easily. But how can I get all subfragments for a given fragment ?
This question is also related to getParentFragment API 16
You can do it in the same way -- just use the FragmentManager
obtained using the Fragment
instance's getChildFragmentManager()
instead of the Activity
FragmentManager
. Of course, this assumes you're using a recompiled version of the support library with getFragments()
not hidden, or are using reflection to get invoke that method.
The following solution is not perfect but it works in some extent :
Here is the solution. The MyActivity class is given below.
public static Fragment getParentFragment(Fragment fragment) {
if( Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN)
return fragment.getParentFragment();
MyActivity activity = (MyActivity)fragment.getActivity();
List<Fragment> fragmentList = activity.getActiveFragments();
if( fragmentList.contains( fragment) ) {
return null;
}
for( Fragment fragmentLevel1 : fragmentList ) {
if( fragmentLevel1.getFragmentManager() == fragment.getFragmentManager() ) {
return fragmentLevel1;
}
}
//this is not supposed to happen, it might be better to throw an exception
return null;
}
Where MyActivity is based on : Is there a way to get references for all currently active fragments in an Activity?
public class MyActivity {
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;
}
}