Signo Signo - 6 months ago 85
Android Question

How to remove fragment from fragment itself

I have an

Activity
which has the possibility to open a gallery, in order to display it I've created a
Fragment
subclass in which I do all of the customization.

The problem i'm facing is that I can't remove the
Fragment
in order to close the gallery.. What I've tried is the following:

closeGallery.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getActivity().getFragmentManager().popBackStack();
}
});


But it doesn't remove the
Fragment
from the
Activity
. What is wrong with the code? Am I missing something in order to be able to remove the
Fragment
?

If it can help here's how I add the
Fragment
to the
Activity
:

frame = new FrameLayout(NewsDetailsActivity.this);
frame.setId(R.id.galleryFragment);
setContentView(frame, new FrameLayout.LayoutParams(
FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));
Bundle bundle = new Bundle();
bundle.putString("gallery", newsDetails.gallery.toString());
Fragment newFragment = new GalleryFragment();
newFragment.setArguments(bundle);
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.add(frame.getId(), newFragment).commit();

ssh ssh
Answer

You missed add to back stack.

FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.add(frame.getId(), newFragment).addToBackStack(null).commit();