How to get a Fragment to remove itself, i.e. its equivalent of finish()?












213















I'm converting an app to use fragments using the compatibility library.
Now currently I have a number of activities (A B C D) which chain onto one another, D has a button 'OK' which when pressed calls finish which then bubbles up through onActivityResult() to additionally destroy C and B.



For my pre Honycomb fragment version each activity is effectively a wrapper on fragments Af Bf Cf Df. All activities are launched via startActivityForResult() and onActivityResult() within each of the fragments can happily call getActivity().finish()



The problem that I am having though is in my Honeycomb version I only have one activity, A, and fragments Bf, Cf, Df are loaded using the FragmentManager.



What I don't understand is what to do in Df when 'OK' is pressed in order to remove fragments Df, Cf, and Bf?



I tried having the fragment popping itself off the stack but this resulted in an exception. onActivityResult() is useless because I have not loaded up the fragment using startActivityForResult().



Am I thinking about this completely the wrong way? Should I be implementing some sort of listener that communicates with either the parent fragment or activity in order to do the pop using the transaction manager?










share|improve this question




















  • 7





    what about ((YourActivity) getActivity()).onBackPressed();

    – Viswanath Lekshmanan
    Mar 10 '15 at 11:44











  • @ViswanathLekshmanan your comment answer is useful for me.. 1 Upvote from me

    – Abhishek Singh
    Nov 28 '16 at 5:24











  • @AbhishekSingh Good to hear :)

    – Viswanath Lekshmanan
    Nov 28 '16 at 7:00











  • @ViswanathLekshmanan :)

    – Abhishek Singh
    Nov 28 '16 at 7:01
















213















I'm converting an app to use fragments using the compatibility library.
Now currently I have a number of activities (A B C D) which chain onto one another, D has a button 'OK' which when pressed calls finish which then bubbles up through onActivityResult() to additionally destroy C and B.



For my pre Honycomb fragment version each activity is effectively a wrapper on fragments Af Bf Cf Df. All activities are launched via startActivityForResult() and onActivityResult() within each of the fragments can happily call getActivity().finish()



The problem that I am having though is in my Honeycomb version I only have one activity, A, and fragments Bf, Cf, Df are loaded using the FragmentManager.



What I don't understand is what to do in Df when 'OK' is pressed in order to remove fragments Df, Cf, and Bf?



I tried having the fragment popping itself off the stack but this resulted in an exception. onActivityResult() is useless because I have not loaded up the fragment using startActivityForResult().



Am I thinking about this completely the wrong way? Should I be implementing some sort of listener that communicates with either the parent fragment or activity in order to do the pop using the transaction manager?










share|improve this question




















  • 7





    what about ((YourActivity) getActivity()).onBackPressed();

    – Viswanath Lekshmanan
    Mar 10 '15 at 11:44











  • @ViswanathLekshmanan your comment answer is useful for me.. 1 Upvote from me

    – Abhishek Singh
    Nov 28 '16 at 5:24











  • @AbhishekSingh Good to hear :)

    – Viswanath Lekshmanan
    Nov 28 '16 at 7:00











  • @ViswanathLekshmanan :)

    – Abhishek Singh
    Nov 28 '16 at 7:01














213












213








213


50






I'm converting an app to use fragments using the compatibility library.
Now currently I have a number of activities (A B C D) which chain onto one another, D has a button 'OK' which when pressed calls finish which then bubbles up through onActivityResult() to additionally destroy C and B.



For my pre Honycomb fragment version each activity is effectively a wrapper on fragments Af Bf Cf Df. All activities are launched via startActivityForResult() and onActivityResult() within each of the fragments can happily call getActivity().finish()



The problem that I am having though is in my Honeycomb version I only have one activity, A, and fragments Bf, Cf, Df are loaded using the FragmentManager.



What I don't understand is what to do in Df when 'OK' is pressed in order to remove fragments Df, Cf, and Bf?



I tried having the fragment popping itself off the stack but this resulted in an exception. onActivityResult() is useless because I have not loaded up the fragment using startActivityForResult().



Am I thinking about this completely the wrong way? Should I be implementing some sort of listener that communicates with either the parent fragment or activity in order to do the pop using the transaction manager?










share|improve this question
















I'm converting an app to use fragments using the compatibility library.
Now currently I have a number of activities (A B C D) which chain onto one another, D has a button 'OK' which when pressed calls finish which then bubbles up through onActivityResult() to additionally destroy C and B.



For my pre Honycomb fragment version each activity is effectively a wrapper on fragments Af Bf Cf Df. All activities are launched via startActivityForResult() and onActivityResult() within each of the fragments can happily call getActivity().finish()



The problem that I am having though is in my Honeycomb version I only have one activity, A, and fragments Bf, Cf, Df are loaded using the FragmentManager.



What I don't understand is what to do in Df when 'OK' is pressed in order to remove fragments Df, Cf, and Bf?



I tried having the fragment popping itself off the stack but this resulted in an exception. onActivityResult() is useless because I have not loaded up the fragment using startActivityForResult().



Am I thinking about this completely the wrong way? Should I be implementing some sort of listener that communicates with either the parent fragment or activity in order to do the pop using the transaction manager?







android






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 20 '18 at 17:08









Carlos Alberto Martínez Gadea

1,25611424




1,25611424










asked May 5 '11 at 16:44









PJLPJL

12.6k136464




12.6k136464








  • 7





    what about ((YourActivity) getActivity()).onBackPressed();

    – Viswanath Lekshmanan
    Mar 10 '15 at 11:44











  • @ViswanathLekshmanan your comment answer is useful for me.. 1 Upvote from me

    – Abhishek Singh
    Nov 28 '16 at 5:24











  • @AbhishekSingh Good to hear :)

    – Viswanath Lekshmanan
    Nov 28 '16 at 7:00











  • @ViswanathLekshmanan :)

    – Abhishek Singh
    Nov 28 '16 at 7:01














  • 7





    what about ((YourActivity) getActivity()).onBackPressed();

    – Viswanath Lekshmanan
    Mar 10 '15 at 11:44











  • @ViswanathLekshmanan your comment answer is useful for me.. 1 Upvote from me

    – Abhishek Singh
    Nov 28 '16 at 5:24











  • @AbhishekSingh Good to hear :)

    – Viswanath Lekshmanan
    Nov 28 '16 at 7:00











  • @ViswanathLekshmanan :)

    – Abhishek Singh
    Nov 28 '16 at 7:01








7




7





what about ((YourActivity) getActivity()).onBackPressed();

– Viswanath Lekshmanan
Mar 10 '15 at 11:44





what about ((YourActivity) getActivity()).onBackPressed();

– Viswanath Lekshmanan
Mar 10 '15 at 11:44













@ViswanathLekshmanan your comment answer is useful for me.. 1 Upvote from me

– Abhishek Singh
Nov 28 '16 at 5:24





@ViswanathLekshmanan your comment answer is useful for me.. 1 Upvote from me

– Abhishek Singh
Nov 28 '16 at 5:24













@AbhishekSingh Good to hear :)

– Viswanath Lekshmanan
Nov 28 '16 at 7:00





@AbhishekSingh Good to hear :)

– Viswanath Lekshmanan
Nov 28 '16 at 7:00













@ViswanathLekshmanan :)

– Abhishek Singh
Nov 28 '16 at 7:01





@ViswanathLekshmanan :)

– Abhishek Singh
Nov 28 '16 at 7:01












10 Answers
10






active

oldest

votes


















55















What I don't understand is what to do in Df when 'OK' is pressed in order to remove fragments Df, Cf, and Bf?




Step #1: Have Df tell D "yo! we got the OK click!" via calling a method, either on the activity itself, or on an interface instance supplied by the activity.



Step #2: Have D remove the fragments via FragmentManager.



The hosting activity (D) is the one that knows what other fragments are in the activity (vs. being in other activities). Hence, in-fragment events that might affect the fragment mix should be propagated to the activity, which will make the appropriate orchestration moves.






share|improve this answer
























  • But in my Honeycomb version there is no D, that's my difficultly. There is simply an activiy A which loads fragment Bf, which loads Cf, which loads Df using FragmentTransaction.

    – PJL
    May 5 '11 at 17:03








  • 1





    @PJL: Sorry, I meant A. This is one reason to use a listener interface, so multiple activities can all respond to the "we got the OK click" event from Df.

    – CommonsWare
    May 5 '11 at 17:18






  • 1





    As I'm currently porting I called a listener method from fragments Df's onActivityResult method into the activity whereupon I then called popBackStack on the FragmentManager. However, this results in an exeption "IllegalStateException: Can not perform this action after onSaveInstanceState'. Any ideas as to how I can overcome this?

    – PJL
    May 6 '11 at 10:53








  • 1





    @DiegoPalomar: finish() should suffice.

    – CommonsWare
    Sep 24 '13 at 19:11






  • 1





    @user3364963: It has been a while since I investigated that, but IIRC, it is destroyed when it is popped off the back stack. Add an onDestroy() method to your fragment and see if it gets called.

    – CommonsWare
    Oct 26 '14 at 23:23



















299














While it might not be the best approach the closest equivalent I can think of that works is this with the support/compatibility library



getActivity().getSupportFragmentManager().beginTransaction().remove(this).commit();


or



getActivity().getFragmentManager().beginTransaction().remove(this).commit();


otherwise.



In addition you can use the backstack and pop it. However keep in mind that the fragment might not be on the backstack (depending on the fragmenttransaction that got it there..) or it might not be the last one that got onto the stack so popping the stack could remove the wrong one...






share|improve this answer





















  • 8





    While this approach works, if you are using addToBackStack(null) it will leave the back button handler +1. So you'll have to press it twice.

    – user123321
    Oct 18 '12 at 1:54






  • 33





    "pop" the fragment from the FragmentManager.

    – user123321
    Oct 25 '12 at 18:34






  • 1





    I have tried the above procedure but it is giving this error "java-lang-illegalstateexception-can-not-perform-this-action-after-onsaveinstance". So where exactly i have to remove the fragment

    – KK_07k11A0585
    Jul 15 '13 at 14:36






  • 5





    This answer is a bad practice and should not be getting up votes. Fragments are not meant to be self-aware like this. It kills reusability, which is the point of fragments! The fragment should signal the activity to remove it through any number of means. The callback interface method is a popular choice. developer.android.com/training/basics/fragments/…

    – colintheshots
    Apr 13 '15 at 16:37






  • 2





    @ManfredMoser I disagree. This is very much the point of the question. He has an entire sequence of fragments to remove. This code has no null checks or checks for whether the activity is attached. It will break in production because it depends upon too many things a fragment does not know.

    – colintheshots
    Apr 13 '15 at 19:00



















253














You can use the approach below, it works fine:



getActivity().getSupportFragmentManager().popBackStack();





share|improve this answer





















  • 43





    This answer is like 10 times better than the accepted one - straight to the point.

    – kape123
    Feb 26 '13 at 5:05








  • 46





    It's also 10 times worse with regards to design than the accepted one. A fragment is supposed to be a small "helper" to an activity and should never bei in control over itself or other fragments

    – avalancha
    Jun 27 '13 at 14:56






  • 6





    The solution is not correct as @avalancha pointed out. Have a look at developer.android.com/guide/components/…

    – the_dark_destructor
    Jul 4 '13 at 20:52






  • 2





    I am using this method onActivityResult and getting error "Can not perform this action after onSaveInstanceState". How can I resolve it?

    – Jayesh Sojitra
    Mar 14 '14 at 11:09








  • 1





    This is working for me.

    – Shafi
    Aug 18 '14 at 12:09



















34














You should let the Activity deal with adding and removing Fragments, as CommonsWare says, use a listener. Here is an example:



public class MyActivity extends FragmentActivity implements SuicidalFragmentListener {

// onCreate etc

@Override
public void onFragmentSuicide(String tag) {
// Check tag if you do this with more than one fragmen, then:
getSupportFragmentManager().popBackStack();
}
}

public interface SuicidalFragmentListener {
void onFragmentSuicide(String tag);
}

public class MyFragment extends Fragment {

// onCreateView etc

@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
suicideListener = (SuicidalFragmentListener) activity;
} catch (ClassCastException e) {
throw new RuntimeException(getActivity().getClass().getSimpleName() + " must implement the suicide listener to use this fragment", e);
}
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Attach the close listener to whatever action on the fragment you want
addSuicideTouchListener();
}

private void addSuicideTouchListener() {
getView().setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
suicideListener.onFragmentSuicide(getTag());
}
});
}
}





share|improve this answer





















  • 4





    Suicide much emo style? How about "SelfClosing" or "AutoClose" or "SmartClose"(r)

    – DritanX
    Apr 8 '14 at 18:02






  • 17





    it's not closing it's DYING FOREVER ;-(

    – Blundell
    Apr 8 '14 at 19:34






  • 2





    This is a much cleaner approach than the other answers. The activity creates and presents the fragment, and should control its lifecycle. When something happens that indicates the fragment should no longer be in view, it should tell the Activity that and let the activity remove it.

    – Christopher Pickslay
    Apr 28 '14 at 23:09






  • 8





    voteup for choosen interface name

    – ruX
    May 12 '15 at 14:33






  • 6





    Technically, if we are to supposed to have the activity kill the fragment, then the fragment isn't suicidal. The activity is homicidal.

    – Casey Murray
    Sep 24 '16 at 23:09





















17














In the Activity/AppCompatActivity:



@Override
public void onBackPressed() {
if (mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
// if you want to handle DrawerLayout
mDrawerLayout.closeDrawer(GravityCompat.START);
} else {
if (getFragmentManager().getBackStackEntryCount() == 0) {
super.onBackPressed();
} else {
getFragmentManager().popBackStack();
}
}
}


and then call in the fragment:



getActivity().onBackPressed();




or like stated in other answers, call this in the fragment:



getActivity().getSupportFragmentManager().beginTransaction().remove(this).commit();





share|improve this answer































    4














    See if your needs are met by a DialogFragment. DialogFragment has a dismiss() method. Much cleaner in my opinion.






    share|improve this answer































      3














      I create simple method for that



      popBackStack(getSupportFragmentManager());


      Than place it in my ActivityUtils class



      public static void popBackStack(FragmentManager manager){
      FragmentManager.BackStackEntry first = manager.getBackStackEntryAt(0);
      manager.popBackStack(first.getId(), FragmentManager.POP_BACK_STACK_INCLUSIVE);
      }


      It's work great, have fun!






      share|improve this answer



















      • 2





        I don't get the purpose of your method. The original popBackStack seems completely adequate.

        – The incredible Jan
        Feb 8 '18 at 14:27



















      1














      OnCreate:



      //Add comment fragment
      container = FindViewById<FrameLayout>(Resource.Id.frmAttachPicture);
      mPictureFragment = new fmtAttachPicture();

      var trans = SupportFragmentManager.BeginTransaction();
      trans.Add(container.Id, mPictureFragment, "fmtPicture");
      trans.Show(mPictureFragment); trans.Commit();


      This is how I hide the fragment in click event 1



      //Close fragment
      var trans = SupportFragmentManager.BeginTransaction();
      trans.Hide(mPictureFragment);
      trans.AddToBackStack(null);
      trans.Commit();


      Then Shows it back int event 2



      var trans = SupportFragmentManager.BeginTransaction();
      trans.Show(mPictureFragment); trans.Commit();





      share|improve this answer































        1














        If you need to popback from the fourth fragment in the backstack history to the first, use tags!!!



        When you add the first fragment you should use something like this:



        getFragmentManager.beginTransaction.addToBackStack("A").add(R.id.container, FragmentA).commit() 


        or



        getFragmentManager.beginTransaction.addToBackStack("A").replace(R.id.container, FragmentA).commit()


        And when you want to show Fragments B,C and D you use this:



        getFragmentManager.beginTransaction.addToBackStack("B").replace(R.id.container, FragmentB, "B").commit()


        and other letters....



        To return to Fragment A, just call popBackStack(0, "A"), yes, use the flag that you specified when you add it, and note that it must be the same flag in the command addToBackStack(), not the one used in command replace or add.



        You're welcome ;)






        share|improve this answer


























        • I have tested 'popBackStack(0, "A")' and my app comes back to fragment A, but I want only that fragment would be removed from Back Stack...How can I remove fragment from Stack without showing in screen??

          – KryNaC
          Jun 19 '15 at 11:28



















        -2














        Why not just:



        getActivity().finish();






        share|improve this answer
























        • This will finish the whole activity not just the fragment.

          – murtadha alsabbagh
          Dec 8 '18 at 11:49











        Your Answer






        StackExchange.ifUsing("editor", function () {
        StackExchange.using("externalEditor", function () {
        StackExchange.using("snippets", function () {
        StackExchange.snippets.init();
        });
        });
        }, "code-snippets");

        StackExchange.ready(function() {
        var channelOptions = {
        tags: "".split(" "),
        id: "1"
        };
        initTagRenderer("".split(" "), "".split(" "), channelOptions);

        StackExchange.using("externalEditor", function() {
        // Have to fire editor after snippets, if snippets enabled
        if (StackExchange.settings.snippets.snippetsEnabled) {
        StackExchange.using("snippets", function() {
        createEditor();
        });
        }
        else {
        createEditor();
        }
        });

        function createEditor() {
        StackExchange.prepareEditor({
        heartbeatType: 'answer',
        autoActivateHeartbeat: false,
        convertImagesToLinks: true,
        noModals: true,
        showLowRepImageUploadWarning: true,
        reputationToPostImages: 10,
        bindNavPrevention: true,
        postfix: "",
        imageUploader: {
        brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
        contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
        allowUrls: true
        },
        onDemand: true,
        discardSelector: ".discard-answer"
        ,immediatelyShowMarkdownHelp:true
        });


        }
        });














        draft saved

        draft discarded


















        StackExchange.ready(
        function () {
        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f5901298%2fhow-to-get-a-fragment-to-remove-itself-i-e-its-equivalent-of-finish%23new-answer', 'question_page');
        }
        );

        Post as a guest















        Required, but never shown

























        10 Answers
        10






        active

        oldest

        votes








        10 Answers
        10






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        55















        What I don't understand is what to do in Df when 'OK' is pressed in order to remove fragments Df, Cf, and Bf?




        Step #1: Have Df tell D "yo! we got the OK click!" via calling a method, either on the activity itself, or on an interface instance supplied by the activity.



        Step #2: Have D remove the fragments via FragmentManager.



        The hosting activity (D) is the one that knows what other fragments are in the activity (vs. being in other activities). Hence, in-fragment events that might affect the fragment mix should be propagated to the activity, which will make the appropriate orchestration moves.






        share|improve this answer
























        • But in my Honeycomb version there is no D, that's my difficultly. There is simply an activiy A which loads fragment Bf, which loads Cf, which loads Df using FragmentTransaction.

          – PJL
          May 5 '11 at 17:03








        • 1





          @PJL: Sorry, I meant A. This is one reason to use a listener interface, so multiple activities can all respond to the "we got the OK click" event from Df.

          – CommonsWare
          May 5 '11 at 17:18






        • 1





          As I'm currently porting I called a listener method from fragments Df's onActivityResult method into the activity whereupon I then called popBackStack on the FragmentManager. However, this results in an exeption "IllegalStateException: Can not perform this action after onSaveInstanceState'. Any ideas as to how I can overcome this?

          – PJL
          May 6 '11 at 10:53








        • 1





          @DiegoPalomar: finish() should suffice.

          – CommonsWare
          Sep 24 '13 at 19:11






        • 1





          @user3364963: It has been a while since I investigated that, but IIRC, it is destroyed when it is popped off the back stack. Add an onDestroy() method to your fragment and see if it gets called.

          – CommonsWare
          Oct 26 '14 at 23:23
















        55















        What I don't understand is what to do in Df when 'OK' is pressed in order to remove fragments Df, Cf, and Bf?




        Step #1: Have Df tell D "yo! we got the OK click!" via calling a method, either on the activity itself, or on an interface instance supplied by the activity.



        Step #2: Have D remove the fragments via FragmentManager.



        The hosting activity (D) is the one that knows what other fragments are in the activity (vs. being in other activities). Hence, in-fragment events that might affect the fragment mix should be propagated to the activity, which will make the appropriate orchestration moves.






        share|improve this answer
























        • But in my Honeycomb version there is no D, that's my difficultly. There is simply an activiy A which loads fragment Bf, which loads Cf, which loads Df using FragmentTransaction.

          – PJL
          May 5 '11 at 17:03








        • 1





          @PJL: Sorry, I meant A. This is one reason to use a listener interface, so multiple activities can all respond to the "we got the OK click" event from Df.

          – CommonsWare
          May 5 '11 at 17:18






        • 1





          As I'm currently porting I called a listener method from fragments Df's onActivityResult method into the activity whereupon I then called popBackStack on the FragmentManager. However, this results in an exeption "IllegalStateException: Can not perform this action after onSaveInstanceState'. Any ideas as to how I can overcome this?

          – PJL
          May 6 '11 at 10:53








        • 1





          @DiegoPalomar: finish() should suffice.

          – CommonsWare
          Sep 24 '13 at 19:11






        • 1





          @user3364963: It has been a while since I investigated that, but IIRC, it is destroyed when it is popped off the back stack. Add an onDestroy() method to your fragment and see if it gets called.

          – CommonsWare
          Oct 26 '14 at 23:23














        55












        55








        55








        What I don't understand is what to do in Df when 'OK' is pressed in order to remove fragments Df, Cf, and Bf?




        Step #1: Have Df tell D "yo! we got the OK click!" via calling a method, either on the activity itself, or on an interface instance supplied by the activity.



        Step #2: Have D remove the fragments via FragmentManager.



        The hosting activity (D) is the one that knows what other fragments are in the activity (vs. being in other activities). Hence, in-fragment events that might affect the fragment mix should be propagated to the activity, which will make the appropriate orchestration moves.






        share|improve this answer














        What I don't understand is what to do in Df when 'OK' is pressed in order to remove fragments Df, Cf, and Bf?




        Step #1: Have Df tell D "yo! we got the OK click!" via calling a method, either on the activity itself, or on an interface instance supplied by the activity.



        Step #2: Have D remove the fragments via FragmentManager.



        The hosting activity (D) is the one that knows what other fragments are in the activity (vs. being in other activities). Hence, in-fragment events that might affect the fragment mix should be propagated to the activity, which will make the appropriate orchestration moves.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered May 5 '11 at 16:57









        CommonsWareCommonsWare

        773k13918891936




        773k13918891936













        • But in my Honeycomb version there is no D, that's my difficultly. There is simply an activiy A which loads fragment Bf, which loads Cf, which loads Df using FragmentTransaction.

          – PJL
          May 5 '11 at 17:03








        • 1





          @PJL: Sorry, I meant A. This is one reason to use a listener interface, so multiple activities can all respond to the "we got the OK click" event from Df.

          – CommonsWare
          May 5 '11 at 17:18






        • 1





          As I'm currently porting I called a listener method from fragments Df's onActivityResult method into the activity whereupon I then called popBackStack on the FragmentManager. However, this results in an exeption "IllegalStateException: Can not perform this action after onSaveInstanceState'. Any ideas as to how I can overcome this?

          – PJL
          May 6 '11 at 10:53








        • 1





          @DiegoPalomar: finish() should suffice.

          – CommonsWare
          Sep 24 '13 at 19:11






        • 1





          @user3364963: It has been a while since I investigated that, but IIRC, it is destroyed when it is popped off the back stack. Add an onDestroy() method to your fragment and see if it gets called.

          – CommonsWare
          Oct 26 '14 at 23:23



















        • But in my Honeycomb version there is no D, that's my difficultly. There is simply an activiy A which loads fragment Bf, which loads Cf, which loads Df using FragmentTransaction.

          – PJL
          May 5 '11 at 17:03








        • 1





          @PJL: Sorry, I meant A. This is one reason to use a listener interface, so multiple activities can all respond to the "we got the OK click" event from Df.

          – CommonsWare
          May 5 '11 at 17:18






        • 1





          As I'm currently porting I called a listener method from fragments Df's onActivityResult method into the activity whereupon I then called popBackStack on the FragmentManager. However, this results in an exeption "IllegalStateException: Can not perform this action after onSaveInstanceState'. Any ideas as to how I can overcome this?

          – PJL
          May 6 '11 at 10:53








        • 1





          @DiegoPalomar: finish() should suffice.

          – CommonsWare
          Sep 24 '13 at 19:11






        • 1





          @user3364963: It has been a while since I investigated that, but IIRC, it is destroyed when it is popped off the back stack. Add an onDestroy() method to your fragment and see if it gets called.

          – CommonsWare
          Oct 26 '14 at 23:23

















        But in my Honeycomb version there is no D, that's my difficultly. There is simply an activiy A which loads fragment Bf, which loads Cf, which loads Df using FragmentTransaction.

        – PJL
        May 5 '11 at 17:03







        But in my Honeycomb version there is no D, that's my difficultly. There is simply an activiy A which loads fragment Bf, which loads Cf, which loads Df using FragmentTransaction.

        – PJL
        May 5 '11 at 17:03






        1




        1





        @PJL: Sorry, I meant A. This is one reason to use a listener interface, so multiple activities can all respond to the "we got the OK click" event from Df.

        – CommonsWare
        May 5 '11 at 17:18





        @PJL: Sorry, I meant A. This is one reason to use a listener interface, so multiple activities can all respond to the "we got the OK click" event from Df.

        – CommonsWare
        May 5 '11 at 17:18




        1




        1





        As I'm currently porting I called a listener method from fragments Df's onActivityResult method into the activity whereupon I then called popBackStack on the FragmentManager. However, this results in an exeption "IllegalStateException: Can not perform this action after onSaveInstanceState'. Any ideas as to how I can overcome this?

        – PJL
        May 6 '11 at 10:53







        As I'm currently porting I called a listener method from fragments Df's onActivityResult method into the activity whereupon I then called popBackStack on the FragmentManager. However, this results in an exeption "IllegalStateException: Can not perform this action after onSaveInstanceState'. Any ideas as to how I can overcome this?

        – PJL
        May 6 '11 at 10:53






        1




        1





        @DiegoPalomar: finish() should suffice.

        – CommonsWare
        Sep 24 '13 at 19:11





        @DiegoPalomar: finish() should suffice.

        – CommonsWare
        Sep 24 '13 at 19:11




        1




        1





        @user3364963: It has been a while since I investigated that, but IIRC, it is destroyed when it is popped off the back stack. Add an onDestroy() method to your fragment and see if it gets called.

        – CommonsWare
        Oct 26 '14 at 23:23





        @user3364963: It has been a while since I investigated that, but IIRC, it is destroyed when it is popped off the back stack. Add an onDestroy() method to your fragment and see if it gets called.

        – CommonsWare
        Oct 26 '14 at 23:23













        299














        While it might not be the best approach the closest equivalent I can think of that works is this with the support/compatibility library



        getActivity().getSupportFragmentManager().beginTransaction().remove(this).commit();


        or



        getActivity().getFragmentManager().beginTransaction().remove(this).commit();


        otherwise.



        In addition you can use the backstack and pop it. However keep in mind that the fragment might not be on the backstack (depending on the fragmenttransaction that got it there..) or it might not be the last one that got onto the stack so popping the stack could remove the wrong one...






        share|improve this answer





















        • 8





          While this approach works, if you are using addToBackStack(null) it will leave the back button handler +1. So you'll have to press it twice.

          – user123321
          Oct 18 '12 at 1:54






        • 33





          "pop" the fragment from the FragmentManager.

          – user123321
          Oct 25 '12 at 18:34






        • 1





          I have tried the above procedure but it is giving this error "java-lang-illegalstateexception-can-not-perform-this-action-after-onsaveinstance". So where exactly i have to remove the fragment

          – KK_07k11A0585
          Jul 15 '13 at 14:36






        • 5





          This answer is a bad practice and should not be getting up votes. Fragments are not meant to be self-aware like this. It kills reusability, which is the point of fragments! The fragment should signal the activity to remove it through any number of means. The callback interface method is a popular choice. developer.android.com/training/basics/fragments/…

          – colintheshots
          Apr 13 '15 at 16:37






        • 2





          @ManfredMoser I disagree. This is very much the point of the question. He has an entire sequence of fragments to remove. This code has no null checks or checks for whether the activity is attached. It will break in production because it depends upon too many things a fragment does not know.

          – colintheshots
          Apr 13 '15 at 19:00
















        299














        While it might not be the best approach the closest equivalent I can think of that works is this with the support/compatibility library



        getActivity().getSupportFragmentManager().beginTransaction().remove(this).commit();


        or



        getActivity().getFragmentManager().beginTransaction().remove(this).commit();


        otherwise.



        In addition you can use the backstack and pop it. However keep in mind that the fragment might not be on the backstack (depending on the fragmenttransaction that got it there..) or it might not be the last one that got onto the stack so popping the stack could remove the wrong one...






        share|improve this answer





















        • 8





          While this approach works, if you are using addToBackStack(null) it will leave the back button handler +1. So you'll have to press it twice.

          – user123321
          Oct 18 '12 at 1:54






        • 33





          "pop" the fragment from the FragmentManager.

          – user123321
          Oct 25 '12 at 18:34






        • 1





          I have tried the above procedure but it is giving this error "java-lang-illegalstateexception-can-not-perform-this-action-after-onsaveinstance". So where exactly i have to remove the fragment

          – KK_07k11A0585
          Jul 15 '13 at 14:36






        • 5





          This answer is a bad practice and should not be getting up votes. Fragments are not meant to be self-aware like this. It kills reusability, which is the point of fragments! The fragment should signal the activity to remove it through any number of means. The callback interface method is a popular choice. developer.android.com/training/basics/fragments/…

          – colintheshots
          Apr 13 '15 at 16:37






        • 2





          @ManfredMoser I disagree. This is very much the point of the question. He has an entire sequence of fragments to remove. This code has no null checks or checks for whether the activity is attached. It will break in production because it depends upon too many things a fragment does not know.

          – colintheshots
          Apr 13 '15 at 19:00














        299












        299








        299







        While it might not be the best approach the closest equivalent I can think of that works is this with the support/compatibility library



        getActivity().getSupportFragmentManager().beginTransaction().remove(this).commit();


        or



        getActivity().getFragmentManager().beginTransaction().remove(this).commit();


        otherwise.



        In addition you can use the backstack and pop it. However keep in mind that the fragment might not be on the backstack (depending on the fragmenttransaction that got it there..) or it might not be the last one that got onto the stack so popping the stack could remove the wrong one...






        share|improve this answer















        While it might not be the best approach the closest equivalent I can think of that works is this with the support/compatibility library



        getActivity().getSupportFragmentManager().beginTransaction().remove(this).commit();


        or



        getActivity().getFragmentManager().beginTransaction().remove(this).commit();


        otherwise.



        In addition you can use the backstack and pop it. However keep in mind that the fragment might not be on the backstack (depending on the fragmenttransaction that got it there..) or it might not be the last one that got onto the stack so popping the stack could remove the wrong one...







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Mar 1 '13 at 1:46

























        answered Feb 22 '12 at 0:01









        Manfred MoserManfred Moser

        24.4k1177117




        24.4k1177117








        • 8





          While this approach works, if you are using addToBackStack(null) it will leave the back button handler +1. So you'll have to press it twice.

          – user123321
          Oct 18 '12 at 1:54






        • 33





          "pop" the fragment from the FragmentManager.

          – user123321
          Oct 25 '12 at 18:34






        • 1





          I have tried the above procedure but it is giving this error "java-lang-illegalstateexception-can-not-perform-this-action-after-onsaveinstance". So where exactly i have to remove the fragment

          – KK_07k11A0585
          Jul 15 '13 at 14:36






        • 5





          This answer is a bad practice and should not be getting up votes. Fragments are not meant to be self-aware like this. It kills reusability, which is the point of fragments! The fragment should signal the activity to remove it through any number of means. The callback interface method is a popular choice. developer.android.com/training/basics/fragments/…

          – colintheshots
          Apr 13 '15 at 16:37






        • 2





          @ManfredMoser I disagree. This is very much the point of the question. He has an entire sequence of fragments to remove. This code has no null checks or checks for whether the activity is attached. It will break in production because it depends upon too many things a fragment does not know.

          – colintheshots
          Apr 13 '15 at 19:00














        • 8





          While this approach works, if you are using addToBackStack(null) it will leave the back button handler +1. So you'll have to press it twice.

          – user123321
          Oct 18 '12 at 1:54






        • 33





          "pop" the fragment from the FragmentManager.

          – user123321
          Oct 25 '12 at 18:34






        • 1





          I have tried the above procedure but it is giving this error "java-lang-illegalstateexception-can-not-perform-this-action-after-onsaveinstance". So where exactly i have to remove the fragment

          – KK_07k11A0585
          Jul 15 '13 at 14:36






        • 5





          This answer is a bad practice and should not be getting up votes. Fragments are not meant to be self-aware like this. It kills reusability, which is the point of fragments! The fragment should signal the activity to remove it through any number of means. The callback interface method is a popular choice. developer.android.com/training/basics/fragments/…

          – colintheshots
          Apr 13 '15 at 16:37






        • 2





          @ManfredMoser I disagree. This is very much the point of the question. He has an entire sequence of fragments to remove. This code has no null checks or checks for whether the activity is attached. It will break in production because it depends upon too many things a fragment does not know.

          – colintheshots
          Apr 13 '15 at 19:00








        8




        8





        While this approach works, if you are using addToBackStack(null) it will leave the back button handler +1. So you'll have to press it twice.

        – user123321
        Oct 18 '12 at 1:54





        While this approach works, if you are using addToBackStack(null) it will leave the back button handler +1. So you'll have to press it twice.

        – user123321
        Oct 18 '12 at 1:54




        33




        33





        "pop" the fragment from the FragmentManager.

        – user123321
        Oct 25 '12 at 18:34





        "pop" the fragment from the FragmentManager.

        – user123321
        Oct 25 '12 at 18:34




        1




        1





        I have tried the above procedure but it is giving this error "java-lang-illegalstateexception-can-not-perform-this-action-after-onsaveinstance". So where exactly i have to remove the fragment

        – KK_07k11A0585
        Jul 15 '13 at 14:36





        I have tried the above procedure but it is giving this error "java-lang-illegalstateexception-can-not-perform-this-action-after-onsaveinstance". So where exactly i have to remove the fragment

        – KK_07k11A0585
        Jul 15 '13 at 14:36




        5




        5





        This answer is a bad practice and should not be getting up votes. Fragments are not meant to be self-aware like this. It kills reusability, which is the point of fragments! The fragment should signal the activity to remove it through any number of means. The callback interface method is a popular choice. developer.android.com/training/basics/fragments/…

        – colintheshots
        Apr 13 '15 at 16:37





        This answer is a bad practice and should not be getting up votes. Fragments are not meant to be self-aware like this. It kills reusability, which is the point of fragments! The fragment should signal the activity to remove it through any number of means. The callback interface method is a popular choice. developer.android.com/training/basics/fragments/…

        – colintheshots
        Apr 13 '15 at 16:37




        2




        2





        @ManfredMoser I disagree. This is very much the point of the question. He has an entire sequence of fragments to remove. This code has no null checks or checks for whether the activity is attached. It will break in production because it depends upon too many things a fragment does not know.

        – colintheshots
        Apr 13 '15 at 19:00





        @ManfredMoser I disagree. This is very much the point of the question. He has an entire sequence of fragments to remove. This code has no null checks or checks for whether the activity is attached. It will break in production because it depends upon too many things a fragment does not know.

        – colintheshots
        Apr 13 '15 at 19:00











        253














        You can use the approach below, it works fine:



        getActivity().getSupportFragmentManager().popBackStack();





        share|improve this answer





















        • 43





          This answer is like 10 times better than the accepted one - straight to the point.

          – kape123
          Feb 26 '13 at 5:05








        • 46





          It's also 10 times worse with regards to design than the accepted one. A fragment is supposed to be a small "helper" to an activity and should never bei in control over itself or other fragments

          – avalancha
          Jun 27 '13 at 14:56






        • 6





          The solution is not correct as @avalancha pointed out. Have a look at developer.android.com/guide/components/…

          – the_dark_destructor
          Jul 4 '13 at 20:52






        • 2





          I am using this method onActivityResult and getting error "Can not perform this action after onSaveInstanceState". How can I resolve it?

          – Jayesh Sojitra
          Mar 14 '14 at 11:09








        • 1





          This is working for me.

          – Shafi
          Aug 18 '14 at 12:09
















        253














        You can use the approach below, it works fine:



        getActivity().getSupportFragmentManager().popBackStack();





        share|improve this answer





















        • 43





          This answer is like 10 times better than the accepted one - straight to the point.

          – kape123
          Feb 26 '13 at 5:05








        • 46





          It's also 10 times worse with regards to design than the accepted one. A fragment is supposed to be a small "helper" to an activity and should never bei in control over itself or other fragments

          – avalancha
          Jun 27 '13 at 14:56






        • 6





          The solution is not correct as @avalancha pointed out. Have a look at developer.android.com/guide/components/…

          – the_dark_destructor
          Jul 4 '13 at 20:52






        • 2





          I am using this method onActivityResult and getting error "Can not perform this action after onSaveInstanceState". How can I resolve it?

          – Jayesh Sojitra
          Mar 14 '14 at 11:09








        • 1





          This is working for me.

          – Shafi
          Aug 18 '14 at 12:09














        253












        253








        253







        You can use the approach below, it works fine:



        getActivity().getSupportFragmentManager().popBackStack();





        share|improve this answer















        You can use the approach below, it works fine:



        getActivity().getSupportFragmentManager().popBackStack();






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Jan 23 '13 at 19:04









        Carsten

        9,08353254




        9,08353254










        answered Jan 23 '13 at 18:39









        Eric YuanEric Yuan

        2,9541912




        2,9541912








        • 43





          This answer is like 10 times better than the accepted one - straight to the point.

          – kape123
          Feb 26 '13 at 5:05








        • 46





          It's also 10 times worse with regards to design than the accepted one. A fragment is supposed to be a small "helper" to an activity and should never bei in control over itself or other fragments

          – avalancha
          Jun 27 '13 at 14:56






        • 6





          The solution is not correct as @avalancha pointed out. Have a look at developer.android.com/guide/components/…

          – the_dark_destructor
          Jul 4 '13 at 20:52






        • 2





          I am using this method onActivityResult and getting error "Can not perform this action after onSaveInstanceState". How can I resolve it?

          – Jayesh Sojitra
          Mar 14 '14 at 11:09








        • 1





          This is working for me.

          – Shafi
          Aug 18 '14 at 12:09














        • 43





          This answer is like 10 times better than the accepted one - straight to the point.

          – kape123
          Feb 26 '13 at 5:05








        • 46





          It's also 10 times worse with regards to design than the accepted one. A fragment is supposed to be a small "helper" to an activity and should never bei in control over itself or other fragments

          – avalancha
          Jun 27 '13 at 14:56






        • 6





          The solution is not correct as @avalancha pointed out. Have a look at developer.android.com/guide/components/…

          – the_dark_destructor
          Jul 4 '13 at 20:52






        • 2





          I am using this method onActivityResult and getting error "Can not perform this action after onSaveInstanceState". How can I resolve it?

          – Jayesh Sojitra
          Mar 14 '14 at 11:09








        • 1





          This is working for me.

          – Shafi
          Aug 18 '14 at 12:09








        43




        43





        This answer is like 10 times better than the accepted one - straight to the point.

        – kape123
        Feb 26 '13 at 5:05







        This answer is like 10 times better than the accepted one - straight to the point.

        – kape123
        Feb 26 '13 at 5:05






        46




        46





        It's also 10 times worse with regards to design than the accepted one. A fragment is supposed to be a small "helper" to an activity and should never bei in control over itself or other fragments

        – avalancha
        Jun 27 '13 at 14:56





        It's also 10 times worse with regards to design than the accepted one. A fragment is supposed to be a small "helper" to an activity and should never bei in control over itself or other fragments

        – avalancha
        Jun 27 '13 at 14:56




        6




        6





        The solution is not correct as @avalancha pointed out. Have a look at developer.android.com/guide/components/…

        – the_dark_destructor
        Jul 4 '13 at 20:52





        The solution is not correct as @avalancha pointed out. Have a look at developer.android.com/guide/components/…

        – the_dark_destructor
        Jul 4 '13 at 20:52




        2




        2





        I am using this method onActivityResult and getting error "Can not perform this action after onSaveInstanceState". How can I resolve it?

        – Jayesh Sojitra
        Mar 14 '14 at 11:09







        I am using this method onActivityResult and getting error "Can not perform this action after onSaveInstanceState". How can I resolve it?

        – Jayesh Sojitra
        Mar 14 '14 at 11:09






        1




        1





        This is working for me.

        – Shafi
        Aug 18 '14 at 12:09





        This is working for me.

        – Shafi
        Aug 18 '14 at 12:09











        34














        You should let the Activity deal with adding and removing Fragments, as CommonsWare says, use a listener. Here is an example:



        public class MyActivity extends FragmentActivity implements SuicidalFragmentListener {

        // onCreate etc

        @Override
        public void onFragmentSuicide(String tag) {
        // Check tag if you do this with more than one fragmen, then:
        getSupportFragmentManager().popBackStack();
        }
        }

        public interface SuicidalFragmentListener {
        void onFragmentSuicide(String tag);
        }

        public class MyFragment extends Fragment {

        // onCreateView etc

        @Override
        public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
        suicideListener = (SuicidalFragmentListener) activity;
        } catch (ClassCastException e) {
        throw new RuntimeException(getActivity().getClass().getSimpleName() + " must implement the suicide listener to use this fragment", e);
        }
        }

        @Override
        public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        // Attach the close listener to whatever action on the fragment you want
        addSuicideTouchListener();
        }

        private void addSuicideTouchListener() {
        getView().setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
        suicideListener.onFragmentSuicide(getTag());
        }
        });
        }
        }





        share|improve this answer





















        • 4





          Suicide much emo style? How about "SelfClosing" or "AutoClose" or "SmartClose"(r)

          – DritanX
          Apr 8 '14 at 18:02






        • 17





          it's not closing it's DYING FOREVER ;-(

          – Blundell
          Apr 8 '14 at 19:34






        • 2





          This is a much cleaner approach than the other answers. The activity creates and presents the fragment, and should control its lifecycle. When something happens that indicates the fragment should no longer be in view, it should tell the Activity that and let the activity remove it.

          – Christopher Pickslay
          Apr 28 '14 at 23:09






        • 8





          voteup for choosen interface name

          – ruX
          May 12 '15 at 14:33






        • 6





          Technically, if we are to supposed to have the activity kill the fragment, then the fragment isn't suicidal. The activity is homicidal.

          – Casey Murray
          Sep 24 '16 at 23:09


















        34














        You should let the Activity deal with adding and removing Fragments, as CommonsWare says, use a listener. Here is an example:



        public class MyActivity extends FragmentActivity implements SuicidalFragmentListener {

        // onCreate etc

        @Override
        public void onFragmentSuicide(String tag) {
        // Check tag if you do this with more than one fragmen, then:
        getSupportFragmentManager().popBackStack();
        }
        }

        public interface SuicidalFragmentListener {
        void onFragmentSuicide(String tag);
        }

        public class MyFragment extends Fragment {

        // onCreateView etc

        @Override
        public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
        suicideListener = (SuicidalFragmentListener) activity;
        } catch (ClassCastException e) {
        throw new RuntimeException(getActivity().getClass().getSimpleName() + " must implement the suicide listener to use this fragment", e);
        }
        }

        @Override
        public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        // Attach the close listener to whatever action on the fragment you want
        addSuicideTouchListener();
        }

        private void addSuicideTouchListener() {
        getView().setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
        suicideListener.onFragmentSuicide(getTag());
        }
        });
        }
        }





        share|improve this answer





















        • 4





          Suicide much emo style? How about "SelfClosing" or "AutoClose" or "SmartClose"(r)

          – DritanX
          Apr 8 '14 at 18:02






        • 17





          it's not closing it's DYING FOREVER ;-(

          – Blundell
          Apr 8 '14 at 19:34






        • 2





          This is a much cleaner approach than the other answers. The activity creates and presents the fragment, and should control its lifecycle. When something happens that indicates the fragment should no longer be in view, it should tell the Activity that and let the activity remove it.

          – Christopher Pickslay
          Apr 28 '14 at 23:09






        • 8





          voteup for choosen interface name

          – ruX
          May 12 '15 at 14:33






        • 6





          Technically, if we are to supposed to have the activity kill the fragment, then the fragment isn't suicidal. The activity is homicidal.

          – Casey Murray
          Sep 24 '16 at 23:09
















        34












        34








        34







        You should let the Activity deal with adding and removing Fragments, as CommonsWare says, use a listener. Here is an example:



        public class MyActivity extends FragmentActivity implements SuicidalFragmentListener {

        // onCreate etc

        @Override
        public void onFragmentSuicide(String tag) {
        // Check tag if you do this with more than one fragmen, then:
        getSupportFragmentManager().popBackStack();
        }
        }

        public interface SuicidalFragmentListener {
        void onFragmentSuicide(String tag);
        }

        public class MyFragment extends Fragment {

        // onCreateView etc

        @Override
        public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
        suicideListener = (SuicidalFragmentListener) activity;
        } catch (ClassCastException e) {
        throw new RuntimeException(getActivity().getClass().getSimpleName() + " must implement the suicide listener to use this fragment", e);
        }
        }

        @Override
        public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        // Attach the close listener to whatever action on the fragment you want
        addSuicideTouchListener();
        }

        private void addSuicideTouchListener() {
        getView().setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
        suicideListener.onFragmentSuicide(getTag());
        }
        });
        }
        }





        share|improve this answer















        You should let the Activity deal with adding and removing Fragments, as CommonsWare says, use a listener. Here is an example:



        public class MyActivity extends FragmentActivity implements SuicidalFragmentListener {

        // onCreate etc

        @Override
        public void onFragmentSuicide(String tag) {
        // Check tag if you do this with more than one fragmen, then:
        getSupportFragmentManager().popBackStack();
        }
        }

        public interface SuicidalFragmentListener {
        void onFragmentSuicide(String tag);
        }

        public class MyFragment extends Fragment {

        // onCreateView etc

        @Override
        public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
        suicideListener = (SuicidalFragmentListener) activity;
        } catch (ClassCastException e) {
        throw new RuntimeException(getActivity().getClass().getSimpleName() + " must implement the suicide listener to use this fragment", e);
        }
        }

        @Override
        public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        // Attach the close listener to whatever action on the fragment you want
        addSuicideTouchListener();
        }

        private void addSuicideTouchListener() {
        getView().setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
        suicideListener.onFragmentSuicide(getTag());
        }
        });
        }
        }






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Nov 20 '13 at 11:19

























        answered Aug 7 '13 at 18:09









        BlundellBlundell

        57.2k27163194




        57.2k27163194








        • 4





          Suicide much emo style? How about "SelfClosing" or "AutoClose" or "SmartClose"(r)

          – DritanX
          Apr 8 '14 at 18:02






        • 17





          it's not closing it's DYING FOREVER ;-(

          – Blundell
          Apr 8 '14 at 19:34






        • 2





          This is a much cleaner approach than the other answers. The activity creates and presents the fragment, and should control its lifecycle. When something happens that indicates the fragment should no longer be in view, it should tell the Activity that and let the activity remove it.

          – Christopher Pickslay
          Apr 28 '14 at 23:09






        • 8





          voteup for choosen interface name

          – ruX
          May 12 '15 at 14:33






        • 6





          Technically, if we are to supposed to have the activity kill the fragment, then the fragment isn't suicidal. The activity is homicidal.

          – Casey Murray
          Sep 24 '16 at 23:09
















        • 4





          Suicide much emo style? How about "SelfClosing" or "AutoClose" or "SmartClose"(r)

          – DritanX
          Apr 8 '14 at 18:02






        • 17





          it's not closing it's DYING FOREVER ;-(

          – Blundell
          Apr 8 '14 at 19:34






        • 2





          This is a much cleaner approach than the other answers. The activity creates and presents the fragment, and should control its lifecycle. When something happens that indicates the fragment should no longer be in view, it should tell the Activity that and let the activity remove it.

          – Christopher Pickslay
          Apr 28 '14 at 23:09






        • 8





          voteup for choosen interface name

          – ruX
          May 12 '15 at 14:33






        • 6





          Technically, if we are to supposed to have the activity kill the fragment, then the fragment isn't suicidal. The activity is homicidal.

          – Casey Murray
          Sep 24 '16 at 23:09










        4




        4





        Suicide much emo style? How about "SelfClosing" or "AutoClose" or "SmartClose"(r)

        – DritanX
        Apr 8 '14 at 18:02





        Suicide much emo style? How about "SelfClosing" or "AutoClose" or "SmartClose"(r)

        – DritanX
        Apr 8 '14 at 18:02




        17




        17





        it's not closing it's DYING FOREVER ;-(

        – Blundell
        Apr 8 '14 at 19:34





        it's not closing it's DYING FOREVER ;-(

        – Blundell
        Apr 8 '14 at 19:34




        2




        2





        This is a much cleaner approach than the other answers. The activity creates and presents the fragment, and should control its lifecycle. When something happens that indicates the fragment should no longer be in view, it should tell the Activity that and let the activity remove it.

        – Christopher Pickslay
        Apr 28 '14 at 23:09





        This is a much cleaner approach than the other answers. The activity creates and presents the fragment, and should control its lifecycle. When something happens that indicates the fragment should no longer be in view, it should tell the Activity that and let the activity remove it.

        – Christopher Pickslay
        Apr 28 '14 at 23:09




        8




        8





        voteup for choosen interface name

        – ruX
        May 12 '15 at 14:33





        voteup for choosen interface name

        – ruX
        May 12 '15 at 14:33




        6




        6





        Technically, if we are to supposed to have the activity kill the fragment, then the fragment isn't suicidal. The activity is homicidal.

        – Casey Murray
        Sep 24 '16 at 23:09







        Technically, if we are to supposed to have the activity kill the fragment, then the fragment isn't suicidal. The activity is homicidal.

        – Casey Murray
        Sep 24 '16 at 23:09













        17














        In the Activity/AppCompatActivity:



        @Override
        public void onBackPressed() {
        if (mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
        // if you want to handle DrawerLayout
        mDrawerLayout.closeDrawer(GravityCompat.START);
        } else {
        if (getFragmentManager().getBackStackEntryCount() == 0) {
        super.onBackPressed();
        } else {
        getFragmentManager().popBackStack();
        }
        }
        }


        and then call in the fragment:



        getActivity().onBackPressed();




        or like stated in other answers, call this in the fragment:



        getActivity().getSupportFragmentManager().beginTransaction().remove(this).commit();





        share|improve this answer




























          17














          In the Activity/AppCompatActivity:



          @Override
          public void onBackPressed() {
          if (mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
          // if you want to handle DrawerLayout
          mDrawerLayout.closeDrawer(GravityCompat.START);
          } else {
          if (getFragmentManager().getBackStackEntryCount() == 0) {
          super.onBackPressed();
          } else {
          getFragmentManager().popBackStack();
          }
          }
          }


          and then call in the fragment:



          getActivity().onBackPressed();




          or like stated in other answers, call this in the fragment:



          getActivity().getSupportFragmentManager().beginTransaction().remove(this).commit();





          share|improve this answer


























            17












            17








            17







            In the Activity/AppCompatActivity:



            @Override
            public void onBackPressed() {
            if (mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
            // if you want to handle DrawerLayout
            mDrawerLayout.closeDrawer(GravityCompat.START);
            } else {
            if (getFragmentManager().getBackStackEntryCount() == 0) {
            super.onBackPressed();
            } else {
            getFragmentManager().popBackStack();
            }
            }
            }


            and then call in the fragment:



            getActivity().onBackPressed();




            or like stated in other answers, call this in the fragment:



            getActivity().getSupportFragmentManager().beginTransaction().remove(this).commit();





            share|improve this answer













            In the Activity/AppCompatActivity:



            @Override
            public void onBackPressed() {
            if (mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
            // if you want to handle DrawerLayout
            mDrawerLayout.closeDrawer(GravityCompat.START);
            } else {
            if (getFragmentManager().getBackStackEntryCount() == 0) {
            super.onBackPressed();
            } else {
            getFragmentManager().popBackStack();
            }
            }
            }


            and then call in the fragment:



            getActivity().onBackPressed();




            or like stated in other answers, call this in the fragment:



            getActivity().getSupportFragmentManager().beginTransaction().remove(this).commit();






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Jan 7 '16 at 15:36









            CodeversedCodeversed

            6,69012937




            6,69012937























                4














                See if your needs are met by a DialogFragment. DialogFragment has a dismiss() method. Much cleaner in my opinion.






                share|improve this answer




























                  4














                  See if your needs are met by a DialogFragment. DialogFragment has a dismiss() method. Much cleaner in my opinion.






                  share|improve this answer


























                    4












                    4








                    4







                    See if your needs are met by a DialogFragment. DialogFragment has a dismiss() method. Much cleaner in my opinion.






                    share|improve this answer













                    See if your needs are met by a DialogFragment. DialogFragment has a dismiss() method. Much cleaner in my opinion.







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Jun 19 '15 at 5:26









                    VasudevVasudev

                    1,1531113




                    1,1531113























                        3














                        I create simple method for that



                        popBackStack(getSupportFragmentManager());


                        Than place it in my ActivityUtils class



                        public static void popBackStack(FragmentManager manager){
                        FragmentManager.BackStackEntry first = manager.getBackStackEntryAt(0);
                        manager.popBackStack(first.getId(), FragmentManager.POP_BACK_STACK_INCLUSIVE);
                        }


                        It's work great, have fun!






                        share|improve this answer



















                        • 2





                          I don't get the purpose of your method. The original popBackStack seems completely adequate.

                          – The incredible Jan
                          Feb 8 '18 at 14:27
















                        3














                        I create simple method for that



                        popBackStack(getSupportFragmentManager());


                        Than place it in my ActivityUtils class



                        public static void popBackStack(FragmentManager manager){
                        FragmentManager.BackStackEntry first = manager.getBackStackEntryAt(0);
                        manager.popBackStack(first.getId(), FragmentManager.POP_BACK_STACK_INCLUSIVE);
                        }


                        It's work great, have fun!






                        share|improve this answer



















                        • 2





                          I don't get the purpose of your method. The original popBackStack seems completely adequate.

                          – The incredible Jan
                          Feb 8 '18 at 14:27














                        3












                        3








                        3







                        I create simple method for that



                        popBackStack(getSupportFragmentManager());


                        Than place it in my ActivityUtils class



                        public static void popBackStack(FragmentManager manager){
                        FragmentManager.BackStackEntry first = manager.getBackStackEntryAt(0);
                        manager.popBackStack(first.getId(), FragmentManager.POP_BACK_STACK_INCLUSIVE);
                        }


                        It's work great, have fun!






                        share|improve this answer













                        I create simple method for that



                        popBackStack(getSupportFragmentManager());


                        Than place it in my ActivityUtils class



                        public static void popBackStack(FragmentManager manager){
                        FragmentManager.BackStackEntry first = manager.getBackStackEntryAt(0);
                        manager.popBackStack(first.getId(), FragmentManager.POP_BACK_STACK_INCLUSIVE);
                        }


                        It's work great, have fun!







                        share|improve this answer












                        share|improve this answer



                        share|improve this answer










                        answered Mar 1 '17 at 12:53









                        EliaszKubalaEliaszKubala

                        2,1741127




                        2,1741127








                        • 2





                          I don't get the purpose of your method. The original popBackStack seems completely adequate.

                          – The incredible Jan
                          Feb 8 '18 at 14:27














                        • 2





                          I don't get the purpose of your method. The original popBackStack seems completely adequate.

                          – The incredible Jan
                          Feb 8 '18 at 14:27








                        2




                        2





                        I don't get the purpose of your method. The original popBackStack seems completely adequate.

                        – The incredible Jan
                        Feb 8 '18 at 14:27





                        I don't get the purpose of your method. The original popBackStack seems completely adequate.

                        – The incredible Jan
                        Feb 8 '18 at 14:27











                        1














                        OnCreate:



                        //Add comment fragment
                        container = FindViewById<FrameLayout>(Resource.Id.frmAttachPicture);
                        mPictureFragment = new fmtAttachPicture();

                        var trans = SupportFragmentManager.BeginTransaction();
                        trans.Add(container.Id, mPictureFragment, "fmtPicture");
                        trans.Show(mPictureFragment); trans.Commit();


                        This is how I hide the fragment in click event 1



                        //Close fragment
                        var trans = SupportFragmentManager.BeginTransaction();
                        trans.Hide(mPictureFragment);
                        trans.AddToBackStack(null);
                        trans.Commit();


                        Then Shows it back int event 2



                        var trans = SupportFragmentManager.BeginTransaction();
                        trans.Show(mPictureFragment); trans.Commit();





                        share|improve this answer




























                          1














                          OnCreate:



                          //Add comment fragment
                          container = FindViewById<FrameLayout>(Resource.Id.frmAttachPicture);
                          mPictureFragment = new fmtAttachPicture();

                          var trans = SupportFragmentManager.BeginTransaction();
                          trans.Add(container.Id, mPictureFragment, "fmtPicture");
                          trans.Show(mPictureFragment); trans.Commit();


                          This is how I hide the fragment in click event 1



                          //Close fragment
                          var trans = SupportFragmentManager.BeginTransaction();
                          trans.Hide(mPictureFragment);
                          trans.AddToBackStack(null);
                          trans.Commit();


                          Then Shows it back int event 2



                          var trans = SupportFragmentManager.BeginTransaction();
                          trans.Show(mPictureFragment); trans.Commit();





                          share|improve this answer


























                            1












                            1








                            1







                            OnCreate:



                            //Add comment fragment
                            container = FindViewById<FrameLayout>(Resource.Id.frmAttachPicture);
                            mPictureFragment = new fmtAttachPicture();

                            var trans = SupportFragmentManager.BeginTransaction();
                            trans.Add(container.Id, mPictureFragment, "fmtPicture");
                            trans.Show(mPictureFragment); trans.Commit();


                            This is how I hide the fragment in click event 1



                            //Close fragment
                            var trans = SupportFragmentManager.BeginTransaction();
                            trans.Hide(mPictureFragment);
                            trans.AddToBackStack(null);
                            trans.Commit();


                            Then Shows it back int event 2



                            var trans = SupportFragmentManager.BeginTransaction();
                            trans.Show(mPictureFragment); trans.Commit();





                            share|improve this answer













                            OnCreate:



                            //Add comment fragment
                            container = FindViewById<FrameLayout>(Resource.Id.frmAttachPicture);
                            mPictureFragment = new fmtAttachPicture();

                            var trans = SupportFragmentManager.BeginTransaction();
                            trans.Add(container.Id, mPictureFragment, "fmtPicture");
                            trans.Show(mPictureFragment); trans.Commit();


                            This is how I hide the fragment in click event 1



                            //Close fragment
                            var trans = SupportFragmentManager.BeginTransaction();
                            trans.Hide(mPictureFragment);
                            trans.AddToBackStack(null);
                            trans.Commit();


                            Then Shows it back int event 2



                            var trans = SupportFragmentManager.BeginTransaction();
                            trans.Show(mPictureFragment); trans.Commit();






                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Jan 9 '18 at 9:34









                            CodeSiCodeSi

                            1015




                            1015























                                1














                                If you need to popback from the fourth fragment in the backstack history to the first, use tags!!!



                                When you add the first fragment you should use something like this:



                                getFragmentManager.beginTransaction.addToBackStack("A").add(R.id.container, FragmentA).commit() 


                                or



                                getFragmentManager.beginTransaction.addToBackStack("A").replace(R.id.container, FragmentA).commit()


                                And when you want to show Fragments B,C and D you use this:



                                getFragmentManager.beginTransaction.addToBackStack("B").replace(R.id.container, FragmentB, "B").commit()


                                and other letters....



                                To return to Fragment A, just call popBackStack(0, "A"), yes, use the flag that you specified when you add it, and note that it must be the same flag in the command addToBackStack(), not the one used in command replace or add.



                                You're welcome ;)






                                share|improve this answer


























                                • I have tested 'popBackStack(0, "A")' and my app comes back to fragment A, but I want only that fragment would be removed from Back Stack...How can I remove fragment from Stack without showing in screen??

                                  – KryNaC
                                  Jun 19 '15 at 11:28
















                                1














                                If you need to popback from the fourth fragment in the backstack history to the first, use tags!!!



                                When you add the first fragment you should use something like this:



                                getFragmentManager.beginTransaction.addToBackStack("A").add(R.id.container, FragmentA).commit() 


                                or



                                getFragmentManager.beginTransaction.addToBackStack("A").replace(R.id.container, FragmentA).commit()


                                And when you want to show Fragments B,C and D you use this:



                                getFragmentManager.beginTransaction.addToBackStack("B").replace(R.id.container, FragmentB, "B").commit()


                                and other letters....



                                To return to Fragment A, just call popBackStack(0, "A"), yes, use the flag that you specified when you add it, and note that it must be the same flag in the command addToBackStack(), not the one used in command replace or add.



                                You're welcome ;)






                                share|improve this answer


























                                • I have tested 'popBackStack(0, "A")' and my app comes back to fragment A, but I want only that fragment would be removed from Back Stack...How can I remove fragment from Stack without showing in screen??

                                  – KryNaC
                                  Jun 19 '15 at 11:28














                                1












                                1








                                1







                                If you need to popback from the fourth fragment in the backstack history to the first, use tags!!!



                                When you add the first fragment you should use something like this:



                                getFragmentManager.beginTransaction.addToBackStack("A").add(R.id.container, FragmentA).commit() 


                                or



                                getFragmentManager.beginTransaction.addToBackStack("A").replace(R.id.container, FragmentA).commit()


                                And when you want to show Fragments B,C and D you use this:



                                getFragmentManager.beginTransaction.addToBackStack("B").replace(R.id.container, FragmentB, "B").commit()


                                and other letters....



                                To return to Fragment A, just call popBackStack(0, "A"), yes, use the flag that you specified when you add it, and note that it must be the same flag in the command addToBackStack(), not the one used in command replace or add.



                                You're welcome ;)






                                share|improve this answer















                                If you need to popback from the fourth fragment in the backstack history to the first, use tags!!!



                                When you add the first fragment you should use something like this:



                                getFragmentManager.beginTransaction.addToBackStack("A").add(R.id.container, FragmentA).commit() 


                                or



                                getFragmentManager.beginTransaction.addToBackStack("A").replace(R.id.container, FragmentA).commit()


                                And when you want to show Fragments B,C and D you use this:



                                getFragmentManager.beginTransaction.addToBackStack("B").replace(R.id.container, FragmentB, "B").commit()


                                and other letters....



                                To return to Fragment A, just call popBackStack(0, "A"), yes, use the flag that you specified when you add it, and note that it must be the same flag in the command addToBackStack(), not the one used in command replace or add.



                                You're welcome ;)







                                share|improve this answer














                                share|improve this answer



                                share|improve this answer








                                edited Nov 20 '18 at 18:03









                                Carlos Alberto Martínez Gadea

                                1,25611424




                                1,25611424










                                answered May 25 '15 at 16:54









                                Diego Ramírez VásquezDiego Ramírez Vásquez

                                358211




                                358211













                                • I have tested 'popBackStack(0, "A")' and my app comes back to fragment A, but I want only that fragment would be removed from Back Stack...How can I remove fragment from Stack without showing in screen??

                                  – KryNaC
                                  Jun 19 '15 at 11:28



















                                • I have tested 'popBackStack(0, "A")' and my app comes back to fragment A, but I want only that fragment would be removed from Back Stack...How can I remove fragment from Stack without showing in screen??

                                  – KryNaC
                                  Jun 19 '15 at 11:28

















                                I have tested 'popBackStack(0, "A")' and my app comes back to fragment A, but I want only that fragment would be removed from Back Stack...How can I remove fragment from Stack without showing in screen??

                                – KryNaC
                                Jun 19 '15 at 11:28





                                I have tested 'popBackStack(0, "A")' and my app comes back to fragment A, but I want only that fragment would be removed from Back Stack...How can I remove fragment from Stack without showing in screen??

                                – KryNaC
                                Jun 19 '15 at 11:28











                                -2














                                Why not just:



                                getActivity().finish();






                                share|improve this answer
























                                • This will finish the whole activity not just the fragment.

                                  – murtadha alsabbagh
                                  Dec 8 '18 at 11:49
















                                -2














                                Why not just:



                                getActivity().finish();






                                share|improve this answer
























                                • This will finish the whole activity not just the fragment.

                                  – murtadha alsabbagh
                                  Dec 8 '18 at 11:49














                                -2












                                -2








                                -2







                                Why not just:



                                getActivity().finish();






                                share|improve this answer













                                Why not just:



                                getActivity().finish();







                                share|improve this answer












                                share|improve this answer



                                share|improve this answer










                                answered Oct 4 '18 at 22:09









                                WillWill

                                5917




                                5917













                                • This will finish the whole activity not just the fragment.

                                  – murtadha alsabbagh
                                  Dec 8 '18 at 11:49



















                                • This will finish the whole activity not just the fragment.

                                  – murtadha alsabbagh
                                  Dec 8 '18 at 11:49

















                                This will finish the whole activity not just the fragment.

                                – murtadha alsabbagh
                                Dec 8 '18 at 11:49





                                This will finish the whole activity not just the fragment.

                                – murtadha alsabbagh
                                Dec 8 '18 at 11:49


















                                draft saved

                                draft discarded




















































                                Thanks for contributing an answer to Stack Overflow!


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid



                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.


                                To learn more, see our tips on writing great answers.




                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function () {
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f5901298%2fhow-to-get-a-fragment-to-remove-itself-i-e-its-equivalent-of-finish%23new-answer', 'question_page');
                                }
                                );

                                Post as a guest















                                Required, but never shown





















































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown

































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown







                                Popular posts from this blog

                                How to send String Array data to Server using php in android

                                Title Spacing in Bjornstrup Chapter, Removing Chapter Number From Contents

                                Is anime1.com a legal site for watching anime?