Handling back button in Android Navigation Component

前端 未结 23 1259
遥遥无期
遥遥无期 2020-11-29 18:20

I\'d like to know how properly handle system back button action using Navigation Controller. In my app I have two fragments (for ex. fragment1 and fragment2) and I have an a

23条回答
  •  有刺的猬
    2020-11-29 19:00

    Depending on your logic, if you want to close only the current fragment you have to pass viewLifecycleOwner, code is shown below:

       requireActivity().onBackPressedDispatcher.addCallback(viewLifecycleOwner, object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                requireActivity().finish()
            }
        })
    

    However, if you want to close application on backPressed no matter from what fragment(probably you wouldn't want that!), don't pass the viewLifecycleOwner. Also if you want to disable the back button, do not do anything inside the handleOnBackPressed(), see below:

     requireActivity().onBackPressedDispatcher.addCallback(viewLifecycleOwner, object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                // do nothing it will disable the back button
            }
        })
    

提交回复
热议问题