0

Anyone please explain, How to define the action in Navigation architecture for header layout of drawer.

snapshot

Now, I need to set click of header of drawer and I set it to like this:

headerOfNavDrawer.setOnClickListener{
    //Here I want to navigate to editProfileFragment
    //But For navigation I need an action in nav arch graph.
    //Where to put action??
}
Rahul
  • 579
  • 1
  • 8
  • 18
  • https://developer.android.com/guide/navigation/navigation-ui#add_a_navigation_drawer – EpicPandaForce Feb 09 '20 at 16:30
  • I have already finished the full setup of the drawer. Issue is that, How to navigate an action in header layout of drawer for launch a fragment. – Rahul Feb 09 '20 at 16:36

1 Answers1

1

You have two things you need:

  1. A reference to the NavController.

As per the Navigate to a destination documentation, you can use findNavController(R.id.your_nav_host_fragment) where R.id.nav_host_fragment is the android:id you put on your NavHostFragment in your Activity's layout.

  1. An action to go to the edit profile fragment.

For this, Navigation allows you to set up global actions - an action that is available from every destination in your graph. This is the correct way of triggering actions from UI provided by your activity.

<navigation xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/main_nav"
        app:startDestination="@id/mainFragment">

  ...

  <action android:id="@+id/action_global_editProfileFragment"
      app:destination="@id/editProfileFragment"/>

</navigation>

When using Safe Args with a global action, this will generate a MainNavDirections class that has your action on it.

This means your completed click listener would look like:

headerOfNavDrawer.setOnClickListener{
    // Use the Kotlin extension in the -ktx artifacts
    val navController = findNavController(R.id.nav_host_fragment)

    // Now use the generated Directions class to navigate to the destination
    navController.navigate(MainNavDirections.actionGlobalEditProfileFragment())
}
ianhanniballake
  • 191,609
  • 30
  • 470
  • 443
  • Thanks for your detailed answer! I resolved this issue using `navController.navigate(resId)` and resId can be a action Id or a destination Id from navigation graph. I resolved this from `NavController.java` class -> `navigate(@IdRes int resId)` method. It says **param resId an action id or a destination id to navigate to a destination** – Rahul Feb 29 '20 at 20:49