skip to Main Content

My MainActivity on start opens SignInFragment, SignIn after succesful auth opens MainFragment. How can I close MainActivity from these two fragments on back pressed? When I tried to add back pressed callback into needed Fragment, it’s closing MainActivity from every fragment, instead of only that one. As well I can’t use popBackStack, since Activity isn’t in BackStack. Is there’s correct sollution to close Activity from needed fragment on back pressed?

2

Answers


  1. There are fews ways to close the activity at onBack pressed, as you are more related to fragment. Firstly create an interface named OnBackPressed and the interface contains the function onBackPressed (any name you would prefer). Implement the interface in the fragments, as it’s function onBackPressed will be defined there, so place activity?.onFinish() in the body of the function.

    First of all, at the MainActivity you override the onBackPress function, and than place the check(if condition).

    override fun onBackPressed(){
    // get the currentFragment
    val currentFragment = supportFragmentManager.findFragmentById(R.id.fragmentID)
    if(currentFragment is OnBackPressedListener){
      currentFragment.onBackPressed()
     } else {
        super.onBackPressed().
     }
    }
    

    This is one of the way you can close the activity when the back button is tapped in the fragment’s.

    Login or Signup to reply.
  2. Sorry for the late replay, Please Use Below code for best practice :

        override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
    
        requireActivity().onBackPressedDispatcher
            .addCallback(this, true) {
                // Handle onBackPressed
                requireActivity().finish()
            }
    

    Just put this code on oncreateView or onViewCreated

       requireActivity().onBackPressedDispatcher
        .addCallback(this, true) {
            // Handle onBackPressed
            requireActivity().finish()
        }
    

    when you click back button, this code will close your parent activity.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search