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)
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.
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.
Try passing your Activity as an activity parameter, then you'll be able to call finish() on it. Hope this helps.
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()).
When working with fragments, instead of using this
or refering to the context, always use getActivity()
. You should call
getActivity().finish();
activity.finish()
to finish your activity from fragment.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With