Home > Blockchain >  Android: Override Navigate Up in App Bar Defined in Fragment
Android: Override Navigate Up in App Bar Defined in Fragment

Time:09-17

I have an app bar using defined from my fragment rather than activity by using

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

        binding.toolbar.apply {
            //add menu
            inflateMenu(R.menu.menu_fragment)

            //setup with navcontroller/navgraph
            setupWithNavController(findNavController())
        }
}

The problem I'm facing is trying to implement a warning message when a user clicks the Navigate Up button using the app bar. I want this behaviour only in one fragment.

I've found solutions online pertaining to app bars defined in an activity but they don't seem to work for me (such as using override fun onSupportNavigateUp(). Any ideas if I may be able to accomplish this?

CodePudding user response:

Quite didn't understand your Question!.

Even though try this for your Navigate Up button Click. requireActivity().onBackPressed()

CodePudding user response:

The problem I'm facing is trying to implement a warning message when a user clicks the Navigate Up button using the app bar. I want this behaviour only in one fragment.

So, you just need to catch the event of hitting the UP button of the app bar for that particular fragment.

You can enable the options menu for that fragment:

setHasOptionsMenu(true)

And override onOptionsItemSelected to catch the UP button id:

override fun onOptionsItemSelected(item: MenuItem): Boolean {
    if (item.itemId == android.R.id.home) {
        // Handle the UP button here
        Toast.makeText(requireContext(), "UP button clicked", Toast.LENGTH_SHORT).show()
        return true
    }
    return super.onOptionsItemSelected(item)
}

Note: if you want to use a unique toolbar for that fragment other than the default one, check this answer.

now I am unable to inflate my menu using inflateMenu(R.menu.menu_fragment). Any ideas?

You can remove this inflation, and instead override onCreateOptionsMenu for that:

override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
    inflater.inflate(R.menu.menu_fragment, menu)
}
  • Related