Kotlin Android App Development Course, Navigation View – Drawer Screen Composition

Android provides several ways to manage screen transitions when creating multi-page applications. One popular method is the Navigation View. In this article, we will delve into how to set up a drawer screen through the Navigation View.

1. What is Navigation View?

The Navigation View is a UI component that helps users easily navigate between different sections of the app. It typically appears by sliding in from the left side of the screen and can be opened by clicking on the hamburger icon at the top or by swiping.

2. Advantages of Navigation View

  • Intuitive Navigation: It clearly displays various sections available for selection, making navigation easy.
  • Space Efficiency: It remains hidden by default and only appears when needed, enhancing screen utilization.
  • Consistent UI: It provides a consistent user experience across various screen configurations.

3. Setting Up Navigation View

Step 1: Project Setup

Open Android Studio and create a new project. Select “Empty Activity” to start with a basic structure. Choose Kotlin as the language, set the package name and save location, then click “Finish” to create the project.

Step 2: Configure Gradle Dependencies

Add the necessary dependencies to use the Navigation View. Open the project’s build.gradle file and add the following library:

    
    dependencies {
        implementation 'com.google.android.material:material:1.5.0'
    }
    

The library above supports Material Design components. Be sure to apply the changes via Gradle Sync afterward.

Step 3: Create XML Layout

Edit the layout file of the main activity, activity_main.xml, to add the Navigation View. Below is an example of the basic structure:

    
    <androidx.drawerlayout.widget.DrawerLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <FrameLayout
            android:id="@+id/content_frame"
            android:layout_width="match_parent"
            android:layout_height="match_parent">
            
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Main Content"
                android:layout_gravity="center"/>

        </FrameLayout>

        <com.google.android.material.navigation.NavigationView
            android:id="@+id/nav_view"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_gravity="start"
            app:headerLayout="@layout/nav_header"
            app:menu="@menu/nav_menu"/>

    </androidx.drawerlayout.widget.DrawerLayout>
    

Step 4: Create Navigation Menu

Set up the required menu items for the Navigation View. Create a res/menu/nav_menu.xml file and add the following content:

    
    <menu xmlns:android="http://schemas.android.com/apk/res/android">
        <item
            android:id="@+id/nav_home"
            android:title="Home"/>
        <item
            android:id="@+id/nav_profile"
            android:title="Profile"/>
        <item
            android:id="@+id/nav_settings"
            android:title="Settings"/>
    </menu>
    

Step 5: Connect Navigation View and Activity

Modify the MainActivity.kt file to connect the Navigation View and main activity. Below is an example that includes basic code:

    
    package com.example.navigationdrawer

    import android.os.Bundle
    import androidx.appcompat.app.AppCompatActivity
    import androidx.drawerlayout.widget.DrawerLayout
    import com.google.android.material.navigation.NavigationView
    import androidx.appcompat.widget.Toolbar
    import android.view.MenuItem
    import android.content.Intent

    class MainActivity : AppCompatActivity() {

        private lateinit var drawerLayout: DrawerLayout
        private lateinit var navView: NavigationView

        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)

            val toolbar: Toolbar = findViewById(R.id.toolbar)
            setSupportActionBar(toolbar)

            drawerLayout = findViewById(R.id.drawer_layout)
            navView = findViewById(R.id.nav_view)

            navView.setNavigationItemSelectedListener { menuItem ->
                when (menuItem.itemId) {
                    R.id.nav_home -> {
                        // Handle home click
                        true
                    }
                    R.id.nav_profile -> {
                        // Handle profile click
                        true
                    }
                    R.id.nav_settings -> {
                        // Handle settings click
                        true
                    }
                    else -> false
                }.also {
                    drawerLayout.closeDrawers() // Close the drawer
                }
            }
        }
    }
    

Step 6: Opening and Closing the Drawer

To open or close the drawer, you need to use user interface elements. It is typically set up to open the drawer by clicking on the hamburger icon in the Toolbar. Add the following code to MainActivity.kt:

    
    toolbar.setNavigationOnClickListener {
        drawerLayout.openDrawer(GravityCompat.START)
    }
    

The above code opens the drawer when the navigation icon (hamburger icon) in the drawer layout is clicked.

4. Managing Multiple Fragments

Let’s also learn how to manage multiple Fragments with the Navigation View. Fragments are independent modules that make up the UI and can be reused across different screen configurations.

Step 1: Create Fragment Classes

First, create Fragment classes. For example, let’s create “HomeFragment”, “ProfileFragment”, and “SettingsFragment”:

    
    class HomeFragment : Fragment() {
        override fun onCreateView(
            inflater: LayoutInflater, container: ViewGroup?,
            savedInstanceState: Bundle?
        ): View? {
            return inflater.inflate(R.layout.fragment_home, container, false)
        }
    }

    class ProfileFragment : Fragment() {
        override fun onCreateView(
            inflater: LayoutInflater, container: ViewGroup?,
            savedInstanceState: Bundle?
        ): View? {
            return inflater.inflate(R.layout.fragment_profile, container, false)
        }
    }

    class SettingsFragment : Fragment() {
        override fun onCreateView(
            inflater: LayoutInflater, container: ViewGroup?,
            savedInstanceState: Bundle?
        ): View? {
            return inflater.inflate(R.layout.fragment_settings, container, false)
        }
    }
    

Step 2: Create Fragment Layout Files

You need to create layout files for each Fragment. Below are examples of XML layout files for each Fragment:

    
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Home Screen"/>
    </LinearLayout>

    <!-- profile.xml -->
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Profile Screen"/>
    </LinearLayout>

    <!-- settings.xml -->
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Settings Screen"/>
    </LinearLayout>
    

Step 3: Handle Fragment Transitions

Write code to switch to the corresponding Fragment when a menu item is clicked. Modify the navView.setNavigationItemSelectedListener part in MainActivity.kt:

    
    navView.setNavigationItemSelectedListener { menuItem ->
        val fragment: Fragment = when (menuItem.itemId) {
            R.id.nav_home -> HomeFragment()
            R.id.nav_profile -> ProfileFragment()
            R.id.nav_settings -> SettingsFragment()
            else -> HomeFragment()
        }
        supportFragmentManager.beginTransaction()
            .replace(R.id.content_frame, fragment)
            .commit()
        drawerLayout.closeDrawer(GravityCompat.START)
        true
    }
    

5. Optimizing Navigation View

There are several methods to optimize the app’s performance. For example, using asynchronous tasks or data caching techniques can make the UI smoother.

Conclusion

You have learned how to use the Navigation View in Android app development with Kotlin to provide an excellent user experience. The Navigation View is one of the essential elements in modern Android apps and is very useful for implementing various user interfaces. I hope you will actively use the Navigation View in your future development processes!

References