Graham
Graham

Reputation: 113

How to fully implement the Navigation Drawer template in Kotlin

I'm expecting this to be a really simple answer. I am developing my first real app on android (a workout tracker) and I am wanting it to have a navigation drawer layout for the majority of the app. I have a bunch of pages that I want the drawer to navigate to. I have figured out how to change the names of the menu items in activity_main_drawer.xml menu file, but I don't know how to attach a navigation to when the user taps on them. My code is the default code from the template:

MainActivity.kt

package com.example.grahamfitnesstracker

import android.os.Bundle
import android.support.design.widget.FloatingActionButton
import android.support.design.widget.Snackbar
import android.support.v4.view.GravityCompat
import android.support.v7.app.ActionBarDrawerToggle
import android.view.MenuItem
import android.support.v4.widget.DrawerLayout
import android.support.design.widget.NavigationView
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.Toolbar
import android.view.Menu

class MainActivity : AppCompatActivity(), NavigationView.OnNavigationItemSelectedListener {


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val toolbar: Toolbar = findViewById(R.id.toolbar)
        setSupportActionBar(toolbar)

        val fab: FloatingActionButton = findViewById(R.id.fab)
        fab.setOnClickListener { view ->
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                .setAction("Action", null).show()
        }
        val drawerLayout: DrawerLayout = findViewById(R.id.drawer_layout)
        val navView: NavigationView = findViewById(R.id.nav_view)
        val toggle = ActionBarDrawerToggle(
            this, drawerLayout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close
        )
        drawerLayout.addDrawerListener(toggle)
        toggle.syncState()

        navView.setNavigationItemSelectedListener(this)
    }

    override fun onBackPressed() {
        val drawerLayout: DrawerLayout = findViewById(R.id.drawer_layout)
        if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
            drawerLayout.closeDrawer(GravityCompat.START)
        } else {
            super.onBackPressed()
        }
    }

    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        // Inflate the menu; this adds items to the action bar if it is present.
        menuInflater.inflate(R.menu.main, menu)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        return when (item.itemId) {
            R.id.action_settings -> true
            else -> super.onOptionsItemSelected(item)
        }
    }

    override fun onNavigationItemSelected(item: MenuItem): Boolean {
        // Handle navigation view item clicks here.
        when (item.itemId) {
            R.id.nav_current_workout -> {
                // Handle the camera action
            }
            R.id.nav_log -> {

            }
            R.id.nav_exercises -> {

            }
            R.id.nav_workouts -> {

            }
            R.id.nav_stats -> {

            }
            R.id.nav_settings -> {

            }
        }
        val drawerLayout: DrawerLayout = findViewById(R.id.drawer_layout)
        drawerLayout.closeDrawer(GravityCompat.START)
        return true
    }
}

And the nav drawer menu activity_main_drawer.xml

<?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/nav_current_workout"
                android:icon="@drawable/ic_menu_play_filled"
                android:title="@string/menu_current_workout"/>
        <item
                android:id="@+id/nav_log"
                android:icon="@drawable/ic_menu_log"
                android:title="@string/menu_log"/>
        <item
                android:id="@+id/nav_exercises"
                android:icon="@drawable/ic_menu_weight"
                android:title="@string/menu_exercises"/>
        <item
                android:id="@+id/nav_workouts"
                android:icon="@drawable/ic_menu_person"
                android:title="@string/menu_workouts"/>
        <item
                android:id="@+id/nav_stats"
                android:icon="@drawable/ic_menu_chart"
                android:title="@string/menu_stats"/>
    </group>
    <item android:title="">
        <menu>
            <item
                    android:id="@+id/nav_settings"
                    android:icon="@drawable/ic_menu_settings"
                    android:title="@string/menu_settings"/>
        </menu>
    </item>

</menu

And finally content_main.xml which I assume is where I need to put fragments (which I still don't fully understand...). From one guide I changed it to including a FrameLayout as:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        tools:showIn="@layout/app_bar_main"
        tools:context=".MainActivity">

    <!-- Note : This is the container Frame Layout for all the fragments-->
    <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/mainFrame">
    </FrameLayout>


</android.support.constraint.ConstraintLayout>

I really just don't know what to add into the onNavigationItemSelected items in MainActivity.kt in order to handle navigation. I have learned that I need to replace the content in content_main.xml with some fragment where I put in my page's ui, but I don't know how to do that. Can anyone help me out? I've looked at a bunch of examples, but they usually implement their own custom nav bars, or are using java which confuses me as a newcomer.

Upvotes: 2

Views: 7547

Answers (2)

murugan mani
murugan mani

Reputation: 485

Xml Layout for navigation drawer:

<include
    layout="@layout/dashboard_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

<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_main"
    app:menu="@menu/drawer_menu" />

Implementation In Kotlin file:

 class MainActivity : 
 AppCompatActivity(),NavigationView.OnNavigationItemSelectedListener {
 private lateinit var drawer: DrawerLayout
 private lateinit var navigationView: NavigationView

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

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

    drawer = findViewById(R.id.drawer_layout)
    toggle = ActionBarDrawerToggle(
        dis,
        drawer,
        toolbar,
        R.string.navigation_drawer_open,
        R.string.navigation_drawer_close
    )
    drawer.addDrawerListener(toggle)
    toggle.setDrawerIndicatorEnabled(true)
    toggle.syncState()

    navigationView = findViewById(R.id.nav_view)
    navigationView.setNavigationItemSelectedListener(dis)

   }

   override fun onNavigationItemSelected(item: MenuItem): Boolean {
    when (item.itemId) {
        R.id.login_signup -> {
        startActivity(Intent(dis, LoginActivity::class.java).putExtra("go_to","0"))
        }
    }
    drawer.closeDrawers()
    return true
   }
 }

Upvotes: 0

SaadAAkash
SaadAAkash

Reputation: 3193

Have you included the NavigationView in your activity_main and add this nav_header_man to that view like this:

activity_main

<?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:openDrawer="start">

    <include
        layout="@layout/app_bar_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <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"

        android:fitsSystemWindows="true"
        app:headerLayout="@layout/nav_header_main"
        app:menu="@menu/activity_main_drawer" >

    </com.google.android.material.navigation.NavigationView>

</androidx.drawerlayout.widget.DrawerLayout>

And since you asked for what to add into the onNavigationItemSelected items in MainActivity.kt,

MainActivity.kt

override fun onNavigationItemSelected(item: MenuItem): Boolean {
        // Handle navigation view item clicks here.
        val i = Intent()
        when (item.itemId) {
            R.id.nav_current_workout -> {
                i.setClass(this, CurrentWorkoutActivity::class.java)
                startActivity(i)
            }
            R.id.nav_log -> {
                //similarly start activity with Intent 
            }
            R.id.nav_exercises -> {}
            R.id.nav_workouts -> {}
            R.id.nav_stats -> {}
            R.id.nav_settings -> {}
        }
        val drawerLayout: DrawerLayout = findViewById(R.id.drawer_layout)
        drawerLayout.closeDrawer(GravityCompat.START)
        return true
    }
}

Hope this helps.

Upvotes: 1

Related Questions