Android Jetpack Navigation: Custom Action for Back Pressed and Nagivate Up in Fragment

October 2, 2019

You should be implementing the following in main activity which enable navigate up.

class MainActivity : AppCompatActivity() {
    override fun onSupportNavigateUp(): Boolean {
        // Allows NavigationUI to support proper up navigation or the drawer layout
        // drawer menu, depending on the situation
        // return navController.navigateUp(drawerLayout)
        return navController.navigateUp()
    }
}

Fragment

class CardFragment : Fragment() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // enable custom menu toolbar
        setHasOptionsMenu(true)
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)

        // handle back button
        requireActivity().onBackPressedDispatcher.addCallback(this) {
            if (viewModel.isEditMode) {
                // do something if in edit mode

            }
            else {
                // else, navigate up as usual
                findNavController().navigateUp()
            }
        }
    }

    override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
        // inflate custom menu
        inflater.inflate(R.menu.card, menu)

        super.onCreateOptionsMenu(menu, inflater)
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        return when(item.itemId) {
            // handle navigateUp
            android.R.id.home -> {
                requireActivity().onBackPressedDispatcher.onBackPressed()
                true
            }
            else -> super.onOptionsItemSelected(item)
        }
    }
}
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.