How to show HomeAsUp when use Android navigation graph

325 Views Asked by At

I have a problem to show HomeAsUp . I think there is such as a way to link NavColtroller with ActionBar. so I don't need to adjust Toolbar manually for each Fragment, mainly when use inclusive return to previous screen.

2

There are 2 best solutions below

0
Maher Abuthraa On

I found the answer

After setup Toolbar add this command in activity:

NavigationUI.setupActionBarWithNavController(this, Navigation.findNavController(this, R.id.nav_host_fragment));

Actually this is not enough .. because HomeAsUp will be visible but not working !

To make it work It's necessary to override this method :

@Override
public boolean onSupportNavigateUp() {
    return Navigation.findNavController(this, R.id.nav_host_fragment).navigateUp()
            || super.onSupportNavigateUp();
}

Dont forget to have proper attributes in graph (popUpTo and popUpToInclusive):

 <fragment
    android:id="@+id/subFragment"
    ...
    >
    <action
        android:id="@+id/action_subFragment_pop"
        app:popUpTo="@id/homeFragment"
        app:popUpToInclusive="true" />
</fragment>
0
Hardik Bambhania On

Below is working for me

layoyt.xml

<ConstraintLayout>
  <Toolbar>
  <fragment>
</ConstraintLayout>

Inside activity.java

private fun setUpToolbar() {
        toolBar = findViewById(R.id.toolbar)
        toolBar.inflateMenu(R.menu.menu)
        setSupportActionBar(toolBar)
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        supportActionBar?.setDisplayShowHomeEnabled(true)
    }