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

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()    }}


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(, menu)        super.onCreateOptionsMenu(menu, inflater)    }    override fun onOptionsItemSelected(item: MenuItem): Boolean {        return when(item.itemId) {            // handle navigateUp   -> {                requireActivity().onBackPressedDispatcher.onBackPressed()                true            }            else -> super.onOptionsItemSelected(item)        }    }}

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.