Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finishing current activity from a fragment

Tags:

android

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)

like image 599
NPike Avatar asked Oct 26 '11 19:10

NPike


People also ask

Can you call an activity from a fragment?

Best way of calling Activity from Fragment class is that make interface in Fragment and add onItemClick() method in that interface. Now implement it to your first activity and call second activity from there.

How do you end a fragment?

If you are using dynamic fragments, set up via a FragmentTransaction , you could run a transaction to replace() the old fragment with the new one.

How do you end an activity in adapter?

Try passing your Activity as an activity parameter, then you'll be able to call finish() on it. Hope this helps.

How do you pass data between fragments and activities?

So, to pass data from the MotherActivity to such a Fragment you will need to create private Strings/Bundles above the onCreate of your Mother activity - which you can fill with the data you want to pass to the fragments, and pass them on via a method created after the onCreate (here called getMyData()).


2 Answers

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.

like image 197
coder_For_Life22 Avatar answered Nov 15 '22 22:11

coder_For_Life22


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.

like image 25
Jon F Hancock Avatar answered Nov 16 '22 00:11

Jon F Hancock