Finishing current activity from a fragment

147,348

Solution 1

When working with fragments, instead of using this or refering to the context, always use getActivity(). You should call

Java

getActivity().finish();

Kotlin

activity.finish()

to finish your activity from fragment.

Solution 2

Well actually...

I wouldn't have the Fragment try to finish the Activity. That places too much authority on the Fragment in my opinion. Instead, I would use the guide here: http://developer.android.com/training/basics/fragments/communicating.html

Have the Fragment define an interface which the Activity must implement. Make a call up to the Activity, then let the Activity decide what to do with the information. If the activity wishes to finish itself, then it can.

Solution 3

As mentioned by Jon F Hancock, this is how a fragment can 'close' the activity by suggesting the activity to close. This makes the fragment portable as is the reason for them. If you use it in a different activity, you might not want to close the activity.

Code below is a snippet from an activity and fragment which has a save and cancel button.

PlayerActivity

public class PlayerActivity extends Activity 
    implements PlayerInfo.PlayerAddListener {

    public void onPlayerCancel() {
       // Decide if its suitable to close the activity, 
       //e.g. is an edit being done in one of the other fragments?
       finish();
    }
}

PlayerInfoFragment, which contains an interface which the calling activity needs to implement.

public class PlayerInfoFragment extends Fragment {
   private PlayerAddListener callback; // implemented in the Activity

   @Override
   public void onAttach(Activity activity) {
     super.onAttach(activity);
     callback= (PlayerAddListener) activity;
   }

   public interface PlayerAddListener {
       public void onPlayerSave(Player p); // not shown in impl above
       public void onPlayerCancel();
   }

   public void btnCancel(View v) {
      callback.onPlayerCancel(); // the activity's implementation
   }
}

Solution 4

You should use getActivity() method in order to finish the activity from the fragment.

getActivity().finish();

Solution 5

In Fragment use getActivity.finishAffinity()

getActivity().finishAffinity();

It will remove all the fragment which pushed by the current activity from the Stack with the Activity too...

Share:
147,348

Related videos on Youtube

NPike
Author by

NPike

Updated on April 29, 2022

Comments

  • NPike
    NPike about 2 years

    I have a fragment in an activity that I am using as a navigation drawer. It contains buttons that when clicked start new activities (startActivity from a fragment simply calls startActivity on the current activity).

    For the life of me I can't seem to figure out how I would finish the current activity after starting a new one.

    I am looking to achieve something like this in the fragment:

    @Override
    public void onClick(View view) {
        // TODO Auto-generated method stub
        if (view == mButtonShows) {
            Intent intent = new Intent(view.getContext(), MyNewActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
            finish();
        } 
    }
    

    But it seems Fragment.class does not implement finish() (like it implements startActivity(...)).

    I would like the activity backstack cleared when they launch the 2nd activity. (so pressing back from the new activity would technically drop them back to the launcher)

  • coder_For_Life22
    coder_For_Life22 over 12 years
    When working with fragments instead of using this or refering to the context, always us getActivity(); when working with fragments
  • Matjaz Kristl
    Matjaz Kristl over 11 years
    getActivity() can be null in some cases. What should we do then?
  • Cristian
    Cristian about 11 years
    @user983956 In such cases the activity is already destroyed, so just don't call finish.
  • Daniel Bejan
    Daniel Bejan almost 10 years
    As a tip : getActivity can be null if you try to use it before inflating the view
  • Sasquatch
    Sasquatch over 9 years
    That's a good point, since a single activity can have multiple fragments present. As you mention, the preferred way for a fragment to communicate back to its activity is via an interface.
  • Ahmed
    Ahmed over 8 years
    The Activity should be the controller/incharge not the fragment, you should rather callback the Activity though a callback interface and let the Activity decide if it should finish itself.
  • user1923551
    user1923551 over 8 years
    Though solutions works correctly, design wise its wrong. fragment should not decide any thing directly, related to parent activity. You should call interaction listener method, intimating that you wanted him(parent activity) to close. Then parent activity will save any data(if there) and closes by using finish().
  • omersem
    omersem almost 8 years
    Also, if you have singletons injected in the activity, do not forget to destroy them, it will create memory leaks, or if there are callbacks remove them ie. , if (getActivity() != null) { getActivity().removeCallbacks(); getActivity().destroy(); }
  • Filipe Brito
    Filipe Brito almost 8 years
    Tell me the diference between your answer and the first answer above (by @coder_For_Life22)...
  • Demotivated
    Demotivated over 6 years
    dont its a trap
  • Zakaria M. Jawas
    Zakaria M. Jawas almost 4 years
    finishAffinity() will remove all the activities that have the same affinity, so activities below the current activity which contains the fragment in the stack could be finished as well.
  • Jamaldin Sabirjanov
    Jamaldin Sabirjanov about 3 years
    Use activity?.finish()
  • Abhishek Dutt
    Abhishek Dutt over 2 years
    This has already been answered. While answering old questions, only do post them if they provide a new solution, is novel and unique.
  • Chris
    Chris about 2 years
    This was already posted in June, 2020