user2573690 user2573690 - 3 months ago 22
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() {
@Override
public void onClick(View view) {
Toast.makeText(getContext(), "Dismissed", Toast.LENGTH_LONG).show();

getActivity().getFragmentManager().popBackStackImmediate();
}
});


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

Thanks in advance!

EDIT:



I am adding my fragment like this:

((MainActivity)context).getSupportFragmentManager().beginTransaction()
.add(R.id.fragment_container, frag).commit();

Answer

try this first add the fragment to backstack like this

FragmentManager fragmentManager = getFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    fragmentTransaction.replace(..............);
    fragmentTransaction.addToBackStack(null);
    fragmentTransaction.commit(); 

Then remove the fragment like this:-

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

to remove all fragments

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