Android SharedPreferences Tutorial and Example

Build a navigation drawer with Fragments

A navigation drawer gives an Android app a familiar place for secondary destinations without crowding the main screen. Opening it reveals menu choices, while the content area remains managed by a Fragment. This pattern suits beginner projects and remains practical when destinations, animations, and back-stack behaviour become more involved.

Using Jetpack’s Navigation Component keeps the menu, graph, toolbar, and Fragment transactions in one coordinated structure. The approach below uses Kotlin, XML views, Material components, and one Activity, giving every screen a clear owner while leaving room for arguments, transitions, and deeper navigation behaviour.

Plan the screen hierarchy

Begin by separating top-level destinations from child screens. A home screen, settings screen, and help screen can live directly in the drawer. A detail screen should normally open from one of those destinations and still contribute to the back stack. This distinction controls which menu items remain selected and when the toolbar shows a back arrow instead of the drawer button.

Navigation Component is preferable to replacing Fragments manually because it owns destination identifiers, arguments, transitions, and back-stack recording. It also lets the drawer and toolbar react to the same graph instead of duplicating click logic.

Concern Manual FragmentManager Navigation Component
Screen changes Explicit transactions Graph-driven destinations
Back behaviour Custom stack handling Recorded automatically
Drawer and toolbar Separate listeners Shared destination state
Testing More branching logic Central navigation rules

Choose the graph before writing the Activity code. Give every drawer destination a stable ID, and make each menu item ID identical to its graph destination ID. The Activity then only connects views to the controller; each Fragment builds and updates its own content.

Create the drawer layout

Add Material, DrawerLayout, and Navigation libraries to the app module. A typical Gradle setup is:

implementation("com.google.android.material:material:1.12.0")
implementation("androidx.drawerlayout:drawerlayout:1.2.0")
implementation("androidx.navigation:navigation-fragment-ktx:2.8.5")
implementation("androidx.navigation:navigation-ui-ktx:2.8.5")

Use a DrawerLayout as the root, a MaterialToolbar above the content, and a NavigationView aligned to start. Using start rather than left keeps the layout correct if right-to-left languages are added later. The Fragment host needs the app-bar scrolling behaviour so its content begins below the toolbar.

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

    <androidx.coordinatorlayout.widget.CoordinatorLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <com.google.android.material.appbar.AppBarLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <com.google.android.material.appbar.MaterialToolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize" />
        </com.google.android.material.appbar.AppBarLayout>

        <androidx.fragment.app.FragmentContainerView
            android:id="@+id/navHostFragment"
            android:name="androidx.navigation.fragment.NavHostFragment"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:defaultNavHost="true"
            app:layout_behavior="@string/appbar_scrolling_view_behavior"
            app:navGraph="@navigation/nav_graph" />
    </androidx.coordinatorlayout.widget.CoordinatorLayout>

    <com.google.android.material.navigation.NavigationView
        android:id="@+id/navigationView"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        app:headerLayout="@layout/nav_header"
        app:menu="@menu/drawer_menu" />
</androidx.drawerlayout.widget.DrawerLayout>

Create res/layout/nav_header.xml with the app name and an optional branded image, then apply a Theme.Material3.DayNight.NoActionBar activity theme because the XML owns the toolbar. Keep the header compact so it does not force small-screen users to scroll before reaching the menu.

Define destinations and menu items

Create res/navigation/nav_graph.xml with the Activity’s start destination, top-level drawer destinations, and one child destination. The action from Home to Details lets the system record the child screen on the back stack.

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

    <fragment
        android:id="@+id/homeFragment"
        android:name="com.example.app.ui.HomeFragment"
        android:label="@string/home">

        <action
            android:id="@+id/action_homeFragment_to_detailsFragment"
            app:destination="@id/detailsFragment" />
    </fragment>

    <fragment
        android:id="@+id/settingsFragment"
        android:name="com.example.app.ui.SettingsFragment"
        android:label="@string/settings" />

    <fragment
        android:id="@+id/helpFragment"
        android:name="com.example.app.ui.HelpFragment"
        android:label="@string/help" />

    <fragment
        android:id="@+id/detailsFragment"
        android:name="com.example.app.ui.DetailsFragment"
        android:label="@string/details" />
</navigation>

Create res/menu/drawer_menu.xml; its IDs deliberately match the graph IDs.

<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <group android:checkableBehavior="single">
        <item
            android:id="@+id/homeFragment"
            android:title="@string/home" />

        <item
            android:id="@+id/settingsFragment"
            android:title="@string/settings" />

        <item
            android:id="@+id/helpFragment"
            android:title="@string/help" />
    </group>
</menu>

Use string resources for labels so they can be translated, and keep drawer items limited to top-level destinations. Details belongs in the graph but not the menu because it depends on the screen that opened it. A product, route, or customer record can pass its ID through a safe argument rather than relying on a shared Activity field.

Connect navigation with Kotlin

In MainActivity, obtain the NavController from the NavHostFragment, declare drawer destinations as top-level, and connect both the toolbar and menu.

class MainActivity : AppCompatActivity() {

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

        val drawerLayout = findViewById<DrawerLayout>(R.id.drawerLayout)
        val toolbar = findViewById<MaterialToolbar>(R.id.toolbar)
        val navigationView = findViewById<NavigationView>(R.id.navigationView)

        setSupportActionBar(toolbar)

        val navHost = supportFragmentManager
            .findFragmentById(R.id.navHostFragment) as NavHostFragment
        val navController = navHost.navController

        val appBarConfiguration = AppBarConfiguration(
            setOf(
                R.id.homeFragment,
                R.id.settingsFragment,
                R.id.helpFragment
            ),
            drawerLayout
        )

        NavigationUI.setupActionBarWithNavController(
            navController,
            appBarConfiguration
        )

        NavigationUI.setupWithNavController(
            navigationView,
            navController,
            drawerLayout
        )
    }
}

AppBarConfiguration defines where the drawer button should appear. NavigationUI updates the toolbar title, selects the correct menu item, opens the drawer, and closes it after navigation. A Fragment button can request a graph action with findNavController().navigate(...); there is no need for FragmentTransaction, replace, or manual back-stack bookkeeping.

Add content and test the experience

Create a layout for each Fragment and point its class at that layout. This small action opens the child Details destination:

class HomeFragment : Fragment(R.layout.fragment_home) {

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        view.findViewById<Button>(R.id.openDetailsButton).setOnClickListener {
            findNavController().navigate(
                R.id.action_homeFragment_to_detailsFragment
            )
        }
    }
}

DetailsFragment, SettingsFragment, and HelpFragment follow the same structure. For an Australian release, use Australian English and familiar commerce and travel formats such as AUD with GST included, DD/MM/YYYY, and kilometres. A Sydney-to-Melbourne journey provides a clear sample, while regional users need the menu to remain usable when mobile coverage is unreliable. Target the Australian Google Play market in the Play Console and check the store listing with the same local wording.

Checks before running

  • Match every drawer menu ID to a navigation graph destination.
  • Include each drawer destination in the AppBarConfiguration set.
  • Confirm labels use string resources and the header remains compact.

Checks on a device

  • Open, scroll, and close the drawer using touch and gesture navigation.
  • Open Details and confirm the system back button returns to Home.
  • Check Australian prices, dates, distances, font scaling, and screen-reader labels.

At this point, the drawer button, highlighted menu item, toolbar title, and Fragment back stack all follow the same navigation graph.