Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle up button inside fragment using Navigation Components

I am making a simple note taking app, I have 2 fragments with navigation component, one fragment has a list of notes and the other is for editing or creating a new note.

In MainActivity I added

val navController = this.findNavController(R.id.host_fragment)
NavigationUI.setupActionBarWithNavController(this, navController)

and then override onSupportNavigateUp()

override fun onSupportNavigateUp(): Boolean {
        val navController = this.findNavController(R.id.host_fragment)
        return navController.navigateUp()
    }

In NoteEditFragment

requireActivity().onBackPressedDispatcher.addCallback(this) {
        saveOrUpdateNote(noteId, note)
    }

now it all works well when pressing the "back button" in the device, However onBackPressedDispatcher.addCallback() is note triggered when I press the "up button" the one on the top left of the screen.

My question is : How do I handle this up button from my NoteEditFragment?

Thanks in advance

like image 360
Yasser Altamimi Avatar asked Aug 24 '19 05:08

Yasser Altamimi


People also ask

How do you call an activity inside a fragment?

Best way of calling Activity from Fragment class is that make interface in Fragment and add onItemClick() method in that interface. Now implement it to your first activity and call second activity from there.


Video Answer


1 Answers

Finally, I found the solution.

First In the activity onCreate method I had to connect the navigation like I did:

val navController = this.findNavController(R.id.host_fragment)
NavigationUI.setupActionBarWithNavController(this, navController)

Then still in MainActivity override onSupportNavigateUp() :

override fun onSupportNavigateUp(): Boolean
{
    val navController = this.findNavController(R.id.host_fragment)
    return navController.navigateUp()
}

Then In the Fragment onCreateView I had to enable option menu:

setHasOptionsMenu(true)

then in the fragment I overridden onOptionsItemSelected :

override fun onOptionsItemSelected(item: MenuItem): Boolean
{
    // handle the up button here
    return NavigationUI.onNavDestinationSelected(item!!,
        view!!.findNavController())
            || super.onOptionsItemSelected(item)
}

Note: I think if you have more than one option menu, then I think you have to do a when (item) statement to check what option has been chosen.

Also if you want to handle the device back button then you can do like this in your fragment onCreateViewMethod :

requireActivity().onBackPressedDispatcher.addCallback(this)
    {
        // handle back button

// change this line to whatever way you chose to navigate back          
findNavController().navigate(NoteEditFragmentDirections.actionNoteEditFragmentToNoteListFragment())
        }
like image 85
Yasser Altamimi Avatar answered Sep 21 '22 20:09

Yasser Altamimi