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 ca
This does not need assertion, Latest update in fragment in android JetPack
requireActivity().finish();
You should use getActivity() method in order to finish the activity from the fragment.
getActivity().finish();
Try this. There shouldn't be any warning...
Activity thisActivity = getActivity();
if (thisActivity != null) {
startActivity(new Intent(thisActivity, yourActivity.class)); // if needed
thisActivity.finish();
}
15 June 2020 - Updated answer.
You have two options for Java and Kotlin. However, logic of both ways are same. You should call activity after call finish() method.
Answer for Kotlin,
If your activity cannot be null, use Answer_1. However, if your activity can be null, use Answer_2.
Answer_1: activity!!.finish()
Answer_2: activity?.finish()
Answer for Java,
getActivity().finish();
@canerkaseler
When working with fragments, instead of using this
or refering to the context, always use getActivity()
. You should call
getActivity().finish();
to finish your activity from fragment.