Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
like image 817
user2573690 Avatar asked Feb 17 '26 14:02

user2573690


2 Answers

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();
}
like image 128
Jagjit Singh Avatar answered Feb 19 '26 03:02

Jagjit Singh


try this

getActivity().getSupportFragmentManager().popBackStack();
like image 34
Uma Achanta Avatar answered Feb 19 '26 02:02

Uma Achanta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!