Navigation Drawer In Android Kotlin With Fragments And Material Design Example

navigation drawer android kotlin, android navigation drawer with fragments

Today’s tutorial is Navigation Drawer Android Kotlin With Fragments And Material Design Example.

Navigation Drawer Android Kotlin example guides you to create a sliding navigation menu with recyclerview.

Navigation Drawer Android Kotlin tutorial uses fragments for navigation purpose.

Visit this for more information about navigation drawer.

First, check the output and then follow all the steps.

Step 1: Create a new project in Android Studio.

Step 2: Update build.gradle(Module:app) file

Add below in build.gradle(Module:app) file

compile 'com.android.support:recyclerview-v7:26.0.2'

Final code for build.gradle(Module:app)

apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "com.example.parsaniahardik.kotlindrawerbasic"
        minSdkVersion 15
        targetSdkVersion 22
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation"org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
    implementation 'com.android.support:appcompat-v7:26.0.2'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'

    compile 'com.android.support:recyclerview-v7:26.0.2'
}

Step 3: Preparing two fragments

Create two fragments and give them name as “FriendListFragment” and “NotificationFragment.

Add below code in fragment_friend_list.xml

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:textSize="30sp"
        android:background="#4aef44"
        android:textColor="#fff"
        android:text="Friends List" />

</FrameLayout>

Add below code in FriendListFragment.kt

import android.os.Bundle
import android.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup


class FriendListFragment : Fragment() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

    }

    override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        // Inflate the layout for this fragment
        return inflater!!.inflate(R.layout.fragment_friend_list, container, false)
    }

}

Copy following source code in fragment_notification.xml

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
   >

    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:textSize="30sp"
        android:background="@color/colorAccent"
        android:textColor="#fff"
        android:text="Notification" />

</FrameLayout>

Copy following code in NotificationFragment.kt

import android.os.Bundle
import android.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup


class NotificationFragment : Fragment() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    }

    override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        // Inflate the layout for this fragment
        return inflater!!.inflate(R.layout.fragment_notification, container, false)
    }
}

Step 4: Adding images

Download images and copy them into “drawable” directory.

Download icons

Step 5: Updating strings.xml and styles.xml

Update string.xml as per below code

<resources>
<string name="app_name">KotlinDrawerBasic</string>

<!-- TODO: Remove or change this placeholder text -->
<string name="drawer_open">Open</string>
<string name="drawer_close">Close</string>
<string name="hello_blank_fragment">Hello blank fragment</string>
</resources>

Update styles.xml as following

<resources>
    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="windowNoTitle">true</item>
        <item name="windowActionBar">false</item>
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>

</resources>

Step 6: Adding toolbar.xml

Create new layout resource file and give it name as “toolbar.xml

Copy below source code in it.

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:local="http://schemas.android.com/apk/res-auto"
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:minHeight="?attr/actionBarSize"
    android:background="?attr/colorPrimary"
    local:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
    local:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

Step 7: Creating lv_item.xml file

Make a new layout resource file named “lv_item.xml

This file is a recyclerview item file. Add below code in it

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:clickable="true">

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/ivicon"
        android:layout_marginLeft="5dp"
        android:layout_marginTop="5dp"
        android:src="@drawable/notification"/>

    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="35dp"
        android:paddingLeft="10dp"
        android:paddingTop="7dp"
        android:text="Noti"
        android:paddingBottom="10dp"
        android:textSize="15dp"
        android:textStyle="bold" />

</LinearLayout>

Step 8: Creating Model

Create a new Kotlin class named “DrawerModel” and add following code

import android.R.attr.name

/**
 * Created by Parsania Hardik on 16-Feb-18.
 */
class DrawerModel {

    var name: String? = null
    var image: Int = 0

    fun getImages(): Int {
        return image
    }

    fun setImages(image: Int) {
        this.image = image
    }

    fun getNames(): String? {
        return name
    }

    fun setNames(name: String) {
        this.name = name
    }

}

Step 9: Making Recyclerview Adapter

Create a new Kotlin class named “DrawerAdapter” and paste below code

/**
 * Created by Parsania Hardik on 16-Feb-18.
 */
import android.content.Context
import android.view.LayoutInflater
import android.support.v7.widget.RecyclerView
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import java.util.ArrayList

class DrawerAdapter(private val context: Context, arrayList: ArrayList<DrawerModel>) : RecyclerView.Adapter<DrawerAdapter.ViewHolder>() {

    internal var arrayList = ArrayList<DrawerModel>()
    private val inflater: LayoutInflater

    init {
        inflater = LayoutInflater.from(context)
        this.arrayList = arrayList
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = inflater.inflate(R.layout.lv_item, parent, false)
        return ViewHolder(view)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {

        holder.title.setText(arrayList[position].getNames())
        holder.ivicon.setImageResource(arrayList[position].getImages())
    }

    override fun getItemCount(): Int {
        return arrayList.size
    }

    inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        var title: TextView
        var ivicon: ImageView

        init {
            title = itemView.findViewById(R.id.name) as TextView
            ivicon = itemView.findViewById(R.id.ivicon) as ImageView
        }
    }
}

Step 10: Creating DrawerFragment

Make a new fragment named DrawerFragment.

Add below source code in fragment_drawer.xml

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

    <RelativeLayout
        android:id="@+id/nav_header_container"
        android:layout_width="match_parent"
        android:layout_height="150dp"
        android:layout_alignParentTop="true"
        android:background="#4fe7ec">

        <ImageView
            android:layout_width="70dp"
            android:layout_height="70dp"
            android:src="@mipmap/ic_launcher"
            android:scaleType="fitCenter"
            android:layout_centerInParent="true" />

    </RelativeLayout>

     <android.support.v7.widget.RecyclerView
        android:id="@+id/listview"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="15dp" />


</LinearLayout>

Add following source code into DrawerFragment.kt

/**
 * Created by Parsania Hardik on 16-Feb-18.
 */
import android.content.Context
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentManager
import android.support.v4.app.FragmentTransaction
import android.support.v4.widget.DrawerLayout
import android.support.v7.app.ActionBarDrawerToggle
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.support.v7.widget.Toolbar
import android.view.GestureDetector
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import java.util.ArrayList


class DrawerFragment : Fragment() {

    private var views: View? = null
    private var mDrawerToggle: ActionBarDrawerToggle? = null
    private var mDrawerLayout: DrawerLayout? = null
    private var drawerAdapter: DrawerAdapter? = null
    private var containerView: View? = null
    private var recyclerView: RecyclerView? = null
    private val names = arrayOf("Friends List", "Notification")
    private val images = intArrayOf(R.drawable.friendlist, R.drawable.notification)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

    }

    override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        // Inflate the layout for this fragment
        views = inflater!!.inflate(R.layout.fragment_drawer, container, false)
        recyclerView = views!!.findViewById<View>(R.id.listview) as RecyclerView
        drawerAdapter = DrawerAdapter(activity, populateList())

        recyclerView!!.adapter = drawerAdapter
        recyclerView!!.layoutManager = LinearLayoutManager(activity)
        recyclerView!!.addOnItemTouchListener(RecyclerTouchListener(activity, recyclerView!!, object : ClickListener {
            override fun onClick(view: View, position: Int) {
                openFragment(position)
                mDrawerLayout!!.closeDrawer(containerView)
            }

            override fun onLongClick(view: View?, position: Int) {

            }
        }))

        openFragment(0)

        return views
    }

    private fun openFragment(position: Int) {

        when (position) {
            0 -> removeAllFragment(FriendListFragment(), "Friends")
            1 -> removeAllFragment(NotificationFragment(), "Notifiaction")

            else -> {
            }
        }
    }

    fun removeAllFragment(replaceFragment: Fragment, tag: String) {
        val manager = activity.supportFragmentManager
        val ft = manager.beginTransaction()
        manager.popBackStackImmediate(null, FragmentManager.POP_BACK_STACK_INCLUSIVE)

        ft.replace(R.id.container_body, replaceFragment)
        ft.commitAllowingStateLoss()
    }

    fun setUpDrawer(fragmentId: Int, drawerLayout: DrawerLayout, toolbar: Toolbar) {
        containerView = activity.findViewById(fragmentId)
        mDrawerLayout = drawerLayout
        mDrawerToggle = object : ActionBarDrawerToggle(activity, drawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close) {
            override fun onDrawerOpened(drawerView: View?) {
                super.onDrawerOpened(drawerView)
                activity.invalidateOptionsMenu()
            }

            override fun onDrawerClosed(drawerView: View?) {
                super.onDrawerClosed(drawerView)
                activity.invalidateOptionsMenu()
            }

            override fun onDrawerSlide(drawerView: View?, slideOffset: Float) {
                super.onDrawerSlide(drawerView, slideOffset)
                toolbar.alpha = 1 - slideOffset / 2
            }
        }

        mDrawerLayout!!.setDrawerListener(mDrawerToggle)
        mDrawerLayout!!.post { mDrawerToggle!!.syncState() }

    }

    private fun populateList(): ArrayList<DrawerModel> {

        val list = ArrayList<DrawerModel>()

        for (i in names.indices) {
            val drawerModel = DrawerModel()
            drawerModel.name = names[i]
            drawerModel.image = images[i]
            list.add(drawerModel)
        }
        return list
    }

    interface ClickListener {
        fun onClick(view: View, position: Int)

        fun onLongClick(view: View?, position: Int)
    }

    internal class RecyclerTouchListener(context: Context, recyclerView: RecyclerView, private val clickListener: ClickListener?) : RecyclerView.OnItemTouchListener {

        private val gestureDetector: GestureDetector

        init {
            gestureDetector = GestureDetector(context, object : GestureDetector.SimpleOnGestureListener() {
                override fun onSingleTapUp(e: MotionEvent): Boolean {
                    return true
                }

                override fun onLongPress(e: MotionEvent) {
                    val child = recyclerView.findChildViewUnder(e.x, e.y)
                    if (child != null && clickListener != null) {
                        clickListener.onLongClick(child, recyclerView.getChildPosition(child))
                    }
                }
            })
        }

        override fun onInterceptTouchEvent(rv: RecyclerView, e: MotionEvent): Boolean {

            val child = rv.findChildViewUnder(e.x, e.y)
            if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {
                clickListener.onClick(child, rv.getChildPosition(child))
            }
            return false
        }

        override fun onTouchEvent(rv: RecyclerView, e: MotionEvent) {}

        override fun onRequestDisallowInterceptTouchEvent(disallowIntercept: Boolean) {

        }
    }
}

Step 11: Description of DrawerFragment.java

In onCreateView() method, recyclerview is initialized and its onClick() method is implemented.

For recyclerview’s onClick() method implementation, a class named RecycletTouchListener and an interface named ClickListener is defined.

openFragment() method will open fragment. Here, a removeAllFragment() method is used to remove all fragments from back stack and open a fresh new fragment.

setUpDrawer() method will be used in MainActivity.

Step 12: Updating MainActivity

Copy below code into activity_main.xml

<android.support.v4.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">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <LinearLayout
            android:id="@+id/container_toolbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <include
                android:id="@+id/toolbar"
                layout="@layout/toolbar" />
        </LinearLayout>

        <FrameLayout
            android:id="@+id/container_body"
            android:layout_width="fill_parent"
            android:layout_height="0dp"
            android:layout_weight="1" />
    </LinearLayout>
    <fragment
        android:id="@+id/fragment_navigation_drawer"
        android:name="com.example.parsaniahardik.kotlindrawerbasic.DrawerFragment"
        android:layout_width="260dp"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        app:layout="@layout/fragment_drawer"
        tools:layout="@layout/fragment_drawer" />

</android.support.v4.widget.DrawerLayout>

Update MainActivity.kt as per following

import android.support.v4.widget.DrawerLayout
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v7.widget.Toolbar
import android.view.View

class MainActivity : AppCompatActivity() {

    private var toolbar: Toolbar? = null
    private var drawerFragment: DrawerFragment? = null

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

        toolbar = findViewById<View>(R.id.toolbar) as Toolbar?

        setSupportActionBar(toolbar)
        supportActionBar!!.setDisplayShowHomeEnabled(true)
        drawerFragment = supportFragmentManager.findFragmentById(R.id.fragment_navigation_drawer) as DrawerFragment
        drawerFragment!!.setUpDrawer(R.id.fragment_navigation_drawer, findViewById<View>(R.id.drawer_layout) as DrawerLayout, toolbar!!)
    }
}

Java Version

Java version of this tutorial : Navigation Drawer Android

Searching Perfect Android Example In Google

Click to get Important Google searching tips

The End for Navigation Drawer In Android Studio example.

Comment if you have queries or want to give a review. Thank you šŸ™‚

Download Source Code For Navigation Drawer Android Kotlin tutorial

[sociallocker]KotlinDrawerBasic[/sociallocker]