How to handle back button when at the starting destination of the navigation component

后端 未结 8 1645
盖世英雄少女心
盖世英雄少女心 2021-01-02 05:01

I\'ve started working with the new navigation component and I\'m really digging it! I do have one issue though - How am I supposed to handle the back button when I\'m at the

8条回答
  •  -上瘾入骨i
    2021-01-02 05:30

    In Jetpack Navigation Componenet, if you want to perform some operation when fragment is poped then you need to override following functions.

    1. Add OnBackPressedCallback in fragment to run your special operation when back is pressed present in system navigation bar at bottom.

       override fun onCreate(savedInstanceState: Bundle?) {
           super.onCreate(savedInstanceState)
      
           onBackPressedCallback = object : OnBackPressedCallback(true) {
               override fun handleOnBackPressed() {
                   //perform your operation and call navigateUp
                  findNavController().navigateUp()
               }
           }
       requireActivity().onBackPressedDispatcher.addCallback(onBackPressedCallback)
       }
      
    2. Add onOptionsItemMenu in fragment to handle back arrow press present at top left corner within the app.

       override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
           super.onViewCreated(view, savedInstanceState)
      
           setHasOptionsMenu(true)
       }
      
      override fun onOptionsItemSelected(item: MenuItem): Boolean {
         if (item.itemId == android.R.id.home) {
             //perform your operation and call navigateUp
             findNavController().navigateUp()
             return true
         }
         return super.onOptionsItemSelected(item)
      }
      
    3. If there is no special code to be run when back is pressed on host fragment then use onSupportNavigateUp in Activity.

       override fun onSupportNavigateUp(): Boolean {
         if (navController.navigateUp() == false){
           //navigateUp() returns false if there are no more fragments to pop
           onBackPressed()
         }
         return navController.navigateUp()
       }
      

    Note that onSupportNavigateUp() is not called if the fragment contains onOptionsItemSelected()

提交回复
热议问题