Skip to main content

How to setup Android Navigation Component with Drawer

How to setup Android Navigation Component with Drawer .
It’s been a wile since Android team launched the new Navigation style in Android . For me , it looks amazingly cool and I thought I should…

It’s been a wile since Android team launched the new Navigation style in Android. For me , it looks amazingly cool and I thought I should share it with you.

Let’s start :

First of all , let’s start with setting up the navigation dependencies :

implementation "androidx.navigation:navigation-fragment-ktx:$rootProject.navigationVersion"
implementation "androidx.navigation:navigation-ui-ktx:$rootProject.navigationVersion"

where navigationVersion is stored in the build.gradle project module:

ext {
navigationVersion = "2.0.0"
...
}

On with the show : 
In your res menu , define a new directory named navigation.

After that, create a nav_graph:

<?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools" android:id="@+id/treasure_nav"
app:startDestination="@id/fragment1">
    <fragment android:id="@+id/fragment1" android:name="com.stavro_xhardha.pockettreasure.Fragment1"
android:label="fragment_fragment1" tools:layout="@layout/fragment_fragment1">
<action android:id="@+id/action_fragment1_to_fragment2" app:destination="@id/fragment2"/>
</fragment>
<fragment android:id="@+id/fragment2" android:name="com.stavro_xhardha.pockettreasure.Fragment2"
android:label="fragment_fragment2" tools:layout="@layout/fragment_fragment2"/>
</navigation>

which basically is the equivalent of this:

Just two fragments connected to each other. What a destination is, is basically the view where I (or the user) needs to be. Since I will be needing to launch something when the app starts, I will define my fragment1 as start destination (never use names like that).

Setting up the main_activity view:

<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context=".MainActivity"
tools:openDrawer="start">
    <LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
        <androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/colorPrimary"
android:theme="@style/ThemeOverlay.MaterialComponents.Dark.ActionBar"/>
        <fragment
android:name="androidx.navigation.fragment.NavHostFragment"
android:id="@+id/nav_host_fragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:defaultNavHost="true"
app:navGraph="@navigation/treasure_nav"/>
</LinearLayout>

    <com.google.android.material.navigation.NavigationView
android:id="@+id/nav_view"
app:menu="@menu/activity_main_drawer"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"/>
</androidx.drawerlayout.widget.DrawerLayout>

Of course , we need these things to setup :

  • The drawer_layout, responsible for holding my menu.
  • The toolbar, responsible for holding my top left icon of the drawer.
  • The nav_host_fragment which will hold any view that I will load from the Navigation logic.
  • The nav_view responsible for my navigation.

Am I done ? Time to setup the logics:

class MainActivity : AppCompatActivity(),
AppBarConfiguration.OnNavigateUpListener {
    private lateinit var appBarConfiguration: AppBarConfiguration;
    override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
        val toolbar = findViewById<Toolbar>(R.id.toolbar)
setSupportActionBar(toolbar) //set the toolbar
        val host: NavHostFragment = supportFragmentManager
.findFragmentById(R.id.nav_host_fragment) as NavHostFragment? ?: return
val navController = host.navController
        appBarConfiguration = AppBarConfiguration(navController.graph) //configure nav controller

        setupNavigation(navController) //setup navigation 
        setupActionBar(navController, appBarConfiguration) // setup action bar
        //hear for event changes
navController.addOnDestinationChangedListener { _, destination, _ ->
val dest: String = try {
resources.getResourceName(destination.id)
} catch (e: Resources.NotFoundException) {
Integer.toString(destination.id)
}
            Toast.makeText(
this@MainActivity, "Navigated to $dest",
Toast.LENGTH_SHORT
).show()
Log.d("NavigationActivity", "Navigated to $dest")
}
}
    private fun setupActionBar(
navController: NavController,
appBarConfig: AppBarConfiguration
) {
setupActionBarWithNavController(navController, appBarConfig)
}
    private fun setupNavigation(navController: NavController) {
val sideNavView = findViewById<NavigationView>(R.id.nav_view)
sideNavView?.setupWithNavController(navController)
        val drawerLayout: DrawerLayout? = findViewById(R.id.drawer_layout)

//fragments load from here but how ?
appBarConfiguration = AppBarConfiguration(
setOf(R.id.fragment1, R.id.fragment2),
drawerLayout
)
}
    override fun onCreateOptionsMenu(menu: Menu): Boolean {
val retValue = super.onCreateOptionsMenu(menu)
val navigationView = findViewById<NavigationView>(R.id.nav_view)
if (navigationView == null) {
//android needs to know what menu I need
menuInflater.inflate(R.menu.activity_main_drawer, menu)
return true
}
return retValue
}
    override fun onOptionsItemSelected(item: MenuItem?): Boolean {
//I need to open the drawer onClick
when (item!!.itemId) {
android.R.id.home ->
drawer_layout.openDrawer(GravityCompat.START)
}
return item.onNavDestinationSelected(findNavController(R.id.nav_host_fragment))
|| super.onOptionsItemSelected(item)
}
    override fun onBackPressed() {
//the code is beautiful enough without comments
if (drawer_layout.isDrawerOpen(GravityCompat.START)) {
drawer_layout.closeDrawer(GravityCompat.START)
} else {
super.onBackPressed()
}
}
}

Hope you noticed my comment here

//fragments load from here but how?

Well this is what I call great.
I don’t even need to define which menu goes where with the new navigation.
But how? 
Go back to the MainActivity and you will notice this line of code: resources.getResourceName(destination.id).
Satisfied enough?

Just place the same id that you added in the nav_graph , and it will work fine.

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:showIn="navigation_view">
    <group android:checkableBehavior="single">
<item
android:id="@+id/fragment1" //here , check the id on the nav_graph now :)
android:icon="@drawable/ic_names_of_god"
android:title="@string/names_of_god"/>
<item
android:id="@+id/fragment2"
android:icon="@drawable/ic_quran"
android:title="@string/quran"/>
<item
android:id="@+id/nav_calendar"
android:icon="@drawable/ic_calendar"
android:title="@string/calendar_and_events"/>
        <item
android:id="@+id/nav_tasbeeh"
android:icon="@drawable/ic_tasbeeh"
android:title="@string/tasbeeh"/>
        <item
android:id="@+id/nav_gallery"
android:icon="@drawable/ic_menu_gallery"
android:title="@string/gallery"/>
        <item
android:id="@+id/nav_news"
android:icon="@drawable/ic_news"
android:title="@string/news"/>
        <item
android:id="@+id/nav_settings"
android:icon="@drawable/ic_settings_dark_grey_24dp"
android:title="@string/action_settings"/>
</group>
    <item android:title="@string/more">
<menu>
<item
android:id="@+id/nav_finish"
android:icon="@drawable/ic_exit_to_app_dark_grey_24dp"
android:title="@string/finish"/>
</menu>
</item>
</menu>

Another thing to note here is the appBarConfiguration = AppBarConfiguration( setOf(R.id.fragment1, R.id.fragment2),
 drawerLayout )
line. Setting both of my fragment1 and fragment2 like that, it means that they will remain on the backstack after navigating to one another. That’s called placing as top level destinations.

Happy Navigating.

Popular posts from this blog

Modularizing your Android app, breaking the monolith (Part 1)

Inspired by a Martin Fowlers post about Micro Frontends, I decided to break my monolithic app into a modular app. I tried to read a little more about breaking monolithic apps in Android, and as far as I got, I felt confident to share my experience with you. This will be some series of blog posts where we actually try to break a simple app into a modularized Android app.

Note: You should know that I am no expert in this, so if there are false statements or mistakes please feel free to criticize, for the sake of a better development. 

What do you benefit from this approach:
Well, people are moving pretty fast nowadays and delivery is required faster and faster. So, in order to achieve this, modularising Android apps is really necessary.You can share features across different apps. Independent teams and less problems per each.Conditional features update.Quicker debugging and fixing.A feature delay doesn't delay the whole app. As per writing tests, there is not too much difference about…

What I learned from Kotlin Flow API

I used to check the docs and just read a lot about flows but didn't implement anything until yesterday. However, the API tasted really cool (even though some operations are still in Experimental state).Prerequisites: If you don't know RxJava it's fine. But a RxJava recognizer would read this faster.Cold vs Hot streamsWell, I really struggled with this concept because it is a little bit tricky. The main difference between cold and hot happened to be pretty simple: Hot streams produce when you don't care while in cold streams, if you don't collect() (or RxJava-s equivalent subscribe()) the stream won't be activated at all. So, Flows are what we call cold streams. Removing the subscriber will not produce data at all, making the Flows one of the most sophisticated asynchronous stream API ever (in the JVM world). I tried to make a illustration of hot and cold streams: Since I mentioned the word asynchronous this implies that they do support coroutines also. Flows vs…

From Gson to Moshi, what I learned

There is no doubt that people are getting away from GSON and I agree with those reasons too. The only advantage GSON has over other parsing libraries is that it takes a really short amount of time to set up. Furthermore, the most important thing is that Moshi is embracing Kotlin support.

First let's implement the dependency:
implementation("com.squareup.moshi:moshi:1.8.0") It's not a struggle to migrate to Moshi. It's really Gson look-a-like. The only thing to do is annotate the object with @field:Json instead of @SerializedName (which is Gsons way for JS representation):

data class User( //GSON way @SerializedName("name") val name: String, @SerializedName("user_name") val userName: String, @SerializedName("last_name") val lastName: String, @SerializedName("email") val email: String ) data class User( //Moshi way @field:Json(name = "name") val name: String, @field:Json(name = "user_name…