Android Implement Sliding Menu Use Navigation View Example

This example show you how to use android.support.design.widget.NavigationView to implement sliding menu when user slide screen or click home icon. It is also based on android.support.v4.widget.DrawerLayout and use the NavigationView as the content for slide out menu.

android implement sliding menu use navigation view example

1. Example Main Layout Xml File.

This is the activity main layout xml file. The root component is DrawerLayout. It contains two child components.

The first component is a LinearLayout which will be shown in activity screen area that includes a Toolbar and another LinearLayout component as fragment replace placeholder.

The second component is the NavigationView object that be displayed in slide menu.

activity_navigation_view.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
    android:id="@+id/navigation_view_drawer_layout"
    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="com.dev2qa.example.material_design.NavigationViewActivity">

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

            <android.support.v7.widget.Toolbar
                android:id="@+id/navigation_view_toolbar"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@color/colorPrimary"
                app:titleTextColor="@color/colorGreen"/>

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

        </LinearLayout>

        <android.support.design.widget.NavigationView
            android:id="@+id/navigation_view_object"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_gravity="start"
            app:headerLayout="@layout/activity_navigation_view_header_layout"
            app:menu="@menu/navigation_view_menu"/>

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

2. NavigationView Introduction.

NavigationView contains two parts, a header part and a menu item list part. From above xml definition, we can see the two parts are defined by two attributes.

  1. app:headerLayout : A layout xml file that is displayed as navigation view header. This file is saved in app / res / layout folder.
  2. app:menu : A menu xml definition file that define the slide menu items. This file is saved in app / res / menu directory.

2.1 NavigationView Header Layout Xml File.

Below is the content of header layout xml configuration. We use a CircleImageView to show a circled image in the header. You can find the detail info in it’s github home page https://github.com/hdodenhof/CircleImageView

Before use CircleImageView and NavigationView, please add below dependency in android project build.gradle file. Do not forget click Sync Now link at top right corner after add below dependency.

compile 'com.android.support:design:26.+'
compile 'de.hdodenhof:circleimageview:2.2.0'

app / res / layout / activity_navigation_view_header_layout.xml

<?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:padding="8dp"
    android:orientation="vertical">

    <de.hdodenhof.circleimageview.CircleImageView
        android:id="@+id/navigation_view_header_image"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:src="@drawable/img6"
        android:layout_centerInParent="true"/>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Finace News Report"
        android:gravity="center"
        android:textSize="20dp"/>

</LinearLayout>

2.2 NavigationView Menu List Definition Xml File.

app / res / menu / navigation_view_menu.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android">
    <group android:checkableBehavior="single">

        <item
            android:id="@+id/navigation_view_news_menu"
            android:icon="@drawable/icon_news_32"
            android:title="News" />

        <item
            android:id="@+id/navigation_view_music_menu"
            android:icon="@drawable/icon_music_32"
            android:title="Music" />

    </group>
</menu>

3. Main Activity.

NavigationViewActivity.java

package com.dev2qa.example.material_design;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;

import com.dev2qa.example.R;

public class NavigationViewActivity extends AppCompatActivity {

    private DrawerLayout drawerLayout = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_navigation_view);

        setTitle("dev2qa.com - Android NavigationView Example.");

        initControls();

        NavigationView navigationView = (NavigationView)findViewById(R.id.navigation_view_object);
        navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {

                int menuItemId = item.getItemId();

                if(menuItemId == R.id.navigation_view_news_menu)
                {
                    Fragment newsFragment = new NavigationViewNewsFragment();
                    replaceFragment(newsFragment);
                }else if(menuItemId == R.id.navigation_view_music_menu)
                {
                    Fragment musicFragment = new NavigationViewMusicFragment();
                    replaceFragment(musicFragment);
                }

                drawerLayout.closeDrawers();
                return false;
            }
        });
    }

    /* Initialize wxample UI controls. */
    private void initControls()
    {
        if(drawerLayout == null)
        {
            drawerLayout = (DrawerLayout)findViewById(R.id.navigation_view_drawer_layout);
        }

        // Get Toolbar and replace activity action bar.
        Toolbar toolbar = (Toolbar)findViewById(R.id.navigation_view_toolbar);
        setSupportActionBar(toolbar);

        ActionBar actionBar = getSupportActionBar();
        if(actionBar != null)
        {
            // Show home icon.
            actionBar.setDisplayHomeAsUpEnabled(true);

            // Set home icon image.
            actionBar.setHomeAsUpIndicator(R.drawable.edit_icon);
        }
    }

    // Replace current Fragment with the destination Fragment.
    public void replaceFragment(Fragment destFragment)
    {
        // First get FragmentManager object.
        FragmentManager fragmentManager = this.getSupportFragmentManager();

        // Begin Fragment transaction.
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

        // Replace the layout holder with the required Fragment object.
        fragmentTransaction.replace(R.id.navigation_view_fragment, destFragment);

        // Commit the Fragment replace action.
        fragmentTransaction.commit();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        int itemId = item.getItemId();

        if(itemId == android.R.id.home)
        {
            drawerLayout.openDrawer(GravityCompat.START);
        }

        return super.onOptionsItemSelected(item);
    }
}

4. News Fragment.

When click the News menu item, activity will display news fragment in activity content area. This is the news fragment related code.

READ :   Android Floating Action Button, Snackbar, List View Example

NavigationViewNewsFragment.java

package com.dev2qa.example.material_design;

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

import com.dev2qa.example.R;

public class NavigationViewNewsFragment extends Fragment {

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

app / res / layout / fragment_navigation_view_news.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"
    tools:context="com.dev2qa.example.material_design.NavigationViewNewsFragment">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="This is the news fragment."
        android:textSize="20dp"
        android:gravity="center"/>

</FrameLayout>

5. Music Fragment.

Similar with news fragment.

NavigationViewMusicFragment.java

package com.dev2qa.example.material_design;

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

import com.dev2qa.example.R;

public class NavigationViewMusicFragment extends Fragment {

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

}

app / res / layout / fragment_navigation_view_music.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"
    tools:context="com.dev2qa.example.material_design.NavigationViewMusicFragment">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="This is the music fragment."
        android:gravity="center"
        android:textSize="20dp"/>

</FrameLayout>

6.Android Manifest Xml File.

AndroidManifest.xml

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

    <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=".material_design.NavigationViewActivity"
            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>

Reference

  1. Android Sliding Menu Using Drawer Layout Example
(Visited 207 times, 1 visits today)

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.