techsolpoint@gmail.com
Sliding Side Menu Using Navigation Drawer with Multiple Fragments – Android Studio

Sliding Side Menu Using Navigation Drawer with Multiple Fragments – Android Studio

We use Sliding Side Menu Using Navigation Drawer in Android to shows your app’s main navigation menu and it’s an important UI component. This menu appears when the user swipes from the left or clicking on drawer icon in the app bar otherwise hidden by default.

In this tutorial, we will create an android app in which implement a Sliding Side Menu Using Navigation Drawer and use multiple fragments which will visible or change according to drawer items click.

Demo

Create A New Project

Before Implementing the following code first create a new project in Android Studio, go to File  => then go to New => then select New Project option. In Add an activity option select Navigation Drawer Activity and proceed.

Run The Project

After successfully project loaded run the application and check your navigation drawer activity is working properly or not. In case of some issues, please check the problem and resolve it before proceeding to the next steps. Try to fix by cleaning and rebuilding the project hope it works. Now we work on some customization in menus and make it functional for fragments change.

Structure Of Code

This following image is showing the project structure.

Navigation Drawer

Code

Code for build.gradle (Module: app )

apply plugin: 'com.android.application'

android {
    compileSdkVersion 27
    defaultConfig {
        applicationId "com.example.asus.navdrawer"
        minSdkVersion 21
        targetSdkVersion 27
        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 'com.android.support:appcompat-v7:27.1.1'
    implementation 'com.android.support:support-v4:27.1.1'
    implementation 'com.android.support:design:27.1.1'
    implementation 'com.android.support.constraint:constraint-layout:1.1.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}

 

Code for AndroidManifest.xml file.

This following code is for the android application Manifest File which is available in your project root directory. The manifest file defines the project structure this is a very important part of the application. 

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.asus.navdrawer">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

 

Code for MainActivity.java file.

This following source code for the MainActivity where we implement some functionality like fragment changes on the click of drawer menus.

package com.example.asus.navdrawer;

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

import com.example.asus.navdrawer.fragment.DbGallery;
import com.example.asus.navdrawer.fragment.DbHome;
import com.example.asus.navdrawer.fragment.DbSlideshow;

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {
    Fragment fragment;
    FragmentTransaction ft;
    DbHome dbHome;
    DbGallery dbGallery;
    DbSlideshow dbSlideshow;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
        loadDbHomefragment();
    }

    private void loadDbHomefragment() {
        dbHome = new DbHome();
        fragment = dbHome;
        ft = getSupportFragmentManager().beginTransaction();
        ft.replace(R.id.db_frame,fragment);
        ft.commitAllowingStateLoss();
    }


    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // 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.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_camera) {

           loadDbHomefragment();

        } else if (id == R.id.nav_gallery) {
            dbGallery = new DbGallery();
            fragment = dbGallery;
            ft = getSupportFragmentManager().beginTransaction();
            ft.replace(R.id.db_frame,fragment);
            ft.commitAllowingStateLoss();

        } else if (id == R.id.nav_slideshow) {

            dbSlideshow = new DbSlideshow();
            fragment = dbSlideshow;
            ft = getSupportFragmentManager().beginTransaction();
            ft.replace(R.id.db_frame,fragment);
            ft.commitAllowingStateLoss();

        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }
}

Code for the activity_main.xml file.

<?xml version="1.0" encoding="utf-8"?>
<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"
    android:fitsSystemWindows="true"
    tools:openDrawer="start">

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

    <android.support.design.widget.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" />

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

Code for the app_bar_main.xml file.

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_main" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        app:srcCompat="@android:drawable/ic_dialog_email" />

</android.support.design.widget.CoordinatorLayout>

Code for the content_main.xml file.

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context=".MainActivity"
    tools:showIn="@layout/app_bar_main">

    <FrameLayout
        android:id="@+id/db_frame"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    </FrameLayout>

</android.support.constraint.ConstraintLayout>

Code for the nav_header_main.xml file.

You can customize or change the navigation drawer header according to you by modification in the code of a nav_header_main.xml file like I have done in this file as below.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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="@dimen/nav_header_height"
    android:background="@drawable/ss"
    android:gravity="bottom"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:theme="@style/ThemeOverlay.AppCompat.Dark">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="60dp"
        android:layout_height="60dp"
        android:contentDescription="@string/nav_header_desc"
        android:paddingTop="@dimen/nav_header_vertical_spacing"
        app:srcCompat="@drawable/logo_t" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingTop="@dimen/nav_header_vertical_spacing"
        android:text="TechSolPoint"
        android:textSize="18sp"
        android:textColor="#FFFFFF"
        android:textAppearance="@style/TextAppearance.AppCompat.Body1" />


</LinearLayout>

Code for the activity_main_drawer.xml file.

In this XML file, we can customize or change menu items. To change or update in the given menus of the drawer go to the menu folder and open the activity_main_drawer.xml file.

<?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_camera"
            android:icon="@drawable/ic_home_black_24dp"
            android:iconTint="#000"
            android:title="Home" />
        <item
            android:id="@+id/nav_gallery"
            android:icon="@drawable/ic_menu_gallery"
            android:iconTint="#000"
            android:title="Gallery" />
        <item
            android:id="@+id/nav_slideshow"
            android:icon="@drawable/ic_menu_slideshow"
            android:iconTint="#000"
            android:title="Slideshow" />
    </group>

</menu>

Create Fragments

Now we create 3 fragments (Home, Gallery, and Slideshow ) and make a functionality for fragment change on click of drawer menus.

Code for DbGallery.java file.

package com.example.asus.navdrawer.fragment;

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

import com.example.asus.navdrawer.R;

public class DbGallery extends Fragment {

    public DbGallery() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_db_gallery, container, false);
    }
}

Code for the fragment_db_gallery.xml file.

<?xml version="1.0" encoding="utf-8"?>
<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"
    android:background="@color/colorAccent"
    tools:context=".fragment.DbGallery">

    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:gravity="center"
        android:textSize="20sp"
        android:textColor="#000000"
        android:textStyle="bold"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="Gallery" />

</FrameLayout>

Code for DbHome.java file.

package com.example.asus.navdrawer.fragment;

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

import com.example.asus.navdrawer.R;

public class DbHome extends Fragment {

    public DbHome() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_db_home, container, false);
    }
}

Code for the fragment_db_home.xml file.

<?xml version="1.0" encoding="utf-8"?>
<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"
    android:background="#317789"
    tools:context=".fragment.DbHome">

    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:gravity="center"
        android:textSize="20sp"
        android:textColor="#FFFFFF"
        android:textStyle="bold"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="Home" />

</FrameLayout>

Code for DbSlideshow.java file.

package com.example.asus.navdrawer.fragment;

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

import com.example.asus.navdrawer.R;

public class DbSlideshow extends Fragment {

    public DbSlideshow() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_db_slideshow, container, false);
    }

}

Code for the fragment_db_slideshow.xml file.

<?xml version="1.0" encoding="utf-8"?>
<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"
    android:background="#307838"
    tools:context=".fragment.DbSlideshow">

    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:gravity="center"
        android:textSize="20sp"
        android:textColor="#FFFFFF"
        android:textStyle="bold"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="Slideshow" />

</FrameLayout>

Final Result Screenshot

Sliding Side Menu

Leave a Reply