I have a MainActivity
with a content_container
to load Fragments
in it.
In one of the Fragment
I also have a sub_container
to load Fragments
.
In the MainActivity
i manage the back button with a stack of Fragment
:
public Fragment addFragmentToStack(Fragment fragment){
if(fragmentStack.size()>MAX_NUM_FRAGMENTS){
fragmentStack.remove(0);
}
return fragmentStack.push(fragment);
}
@Override
public void onBackPressed() {
if (fragmentStack.size() > 0) {
fragmentStack.pop();
if (MyApplication.fragmentStack.size() > 0) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_container, fragmentStack.peek());
ft.commit();
}
}
}
and whenever I want to replace a Fragment
in my content_container
I use
Fragment someFragment = new SomeFragment();
fragmentTransaction.replace(R.id.content_container, ((MainActivity)getActivity()).addFragmentToStack(someFragment), "");
fragmentTransaction.commit();
One Fragment
is a gallery, with a menu to load a photos
or a videos
Fragment
in it (so the gallery is the parent Fragment
and the photos and videos Fragments
are children).
In order to be able to add the photo gallery and the video gallery in the stack, I use in the GalleryFragment:
if(mType.equals("photos")){
Fragment videoFragment = new VideoFragment();
fragmentTransaction.replace(R.id.sub_container, videoFragment, "");
((MainActivity)getActivity()).addFragmentToStack(this);
}
else{
Fragment photoFragment = new PhotoFragment();
fragmentTransaction.replace(R.id.sub_container, photoFragment, "");
((MainActivity)getActivity()).addFragmentToStack(this);
}
i.e. I add the parent GalleryFragment
in the stack.
When I go from the videos to the photos gallery, for instance, and press the back Button
, the code in MainActivity
's onBackPressed
is executed, and the current GalleryFragment
instance is replaced by the instance in the stack, but its sub_container
is empty (none of onCreateView
or onResume
is called).
Anybody can help?