Handling back button in Android Navigation Component

前端 未结 23 1347
遥遥无期
遥遥无期 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:16

    Here is my solution

    Use androidx.appcompat.app.AppCompatActivity for the activity that contains the NavHostFragment fragment.

    Define the following interface and implement it in all navigation destination fragments

    interface InterceptionInterface {
    
        fun onNavigationUp(): Boolean
        fun onBackPressed(): Boolean
    }
    

    In your activity override onSupportNavigateUp and onBackPressed:

    override fun onSupportNavigateUp(): Boolean {
            return getCurrentNavDest().onNavigationUp() || navigation_host_fragment.findNavController().navigateUp()
    }
    
    override fun onBackPressed() {
            if (!getCurrentNavDest().onBackPressed()){
                super.onBackPressed()
            }
    }
    
    private fun getCurrentNavDest(): InterceptionInterface {
            val currentFragment = navigation_host_fragment.childFragmentManager.primaryNavigationFragment as InterceptionInterface
            return currentFragment
    }
    

    This solution has the advantage, that the navigation destination fragments don't need to worry about the unregistering of their listeners as soon as they are detached.

提交回复
热议问题