Finishing current activity from a fragment

前端 未结 11 1495
野的像风
野的像风 2020-12-13 02:02

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

相关标签:
11条回答
  • 2020-12-13 02:27

    This does not need assertion, Latest update in fragment in android JetPack

    requireActivity().finish();
    
    0 讨论(0)
  • 2020-12-13 02:30

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

    getActivity().finish();
    
    0 讨论(0)
  • 2020-12-13 02:33

    Try this. There shouldn't be any warning...

                Activity thisActivity = getActivity();
                if (thisActivity != null) {
                    startActivity(new Intent(thisActivity, yourActivity.class)); // if needed
                    thisActivity.finish();
                }
    
    0 讨论(0)
  • 2020-12-13 02:36

    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

    0 讨论(0)
  • 2020-12-13 02:39

    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.

    0 讨论(0)
提交回复
热议问题