user2573690 user2573690 - 6 months ago 50
Android Question

Remove fragment from activity when clicking button?

Currently, my main activity has a description field which opens a fragment when the user clicks on the description. On the fragment there is a text field and a button, when I click the button, I want to close the fragment and go back to my activity.

How can I achieve this?

I have added an onClickListener to my fragment to capture the click on the button. The toast message gets printed, but the fragment is not removed/closed.

descDismiss.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Toast.makeText(getContext(), "Dismissed", Toast.LENGTH_LONG).show();


I have the onClickListener in the onCreateView of the fragment. Is this correct?

Thanks in advance!


I am adding my fragment like this:

.add(, frag).commit();


try this first add the fragment to backstack like this

FragmentManager fragmentManager = getFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

Then remove the fragment like this:-

FragmentManager fm = getActivity().getSupportFragmentManager();
      if(fm.getBackStackEntryCount()>0) {

to remove all fragments

FragmentManager fm = getActivity().getSupportFragmentManager();
      for (int i = 0; i < fm.getBackStackEntryCount(); ++i) {