javaandroidandroid-studioonbackpressed

onBackPressed() is not working in Fragment


I want to completely it goes to the home of the phone when i back, but onBackPressed() is not working. My Page is a fragment btw.


Solution

  • Use getActivity().onBackPressed(); in your fragment it will execute onBackPressed() of your parent activity

    to be more accurate

    Activity activity = getActivity();
        if (activity != null) {
            activity.onBackPressed();}
    

    edit: use requireActivity() for avoiding nullpointer

    requireActivity().onBackPressed();