Android Sliding Menu Using Drawer Layout Example

android.support.v4.widget.DrawerLayout is a android layout which follow material design pattern. It is used to implement slide in / out menu animation in android application. This article will show you an example about how to use it.

android sliding menu using drawer layout example

When click the home button ( green plus button ) or slide screen to right, the drawer popup menu list will slide out.

Click each menu item, the menu item title will be displayed in the activity content area.

1. How To Use DrawerLayout.

DrawerLayout contains two sub components ( xml element ) in general. The first element is the content of the activity, the second xml element is the content of the popup drawer content. You can add any android view object for the first and second component.

In our example , the first element is a LinearLayout that contain a Toolbar and a TextView in vertical order. The second element is a ListView which will be used to display drawer slide menu items.

All the components is defined in the activity layout xml file as below.

activity_drawer_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
    android:id="@+id/drawer_layout_widget"
    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.DrawerLayoutActivity">

        <!-- Screen UI component. -->
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <android.supporta.v7.widget.Toolbar
                android:id="@+id/drawer_layout_toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:background="@color/colorPrimary"
                app:titleTextColor="@color/colorGreen"
                app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

            <TextView
                android:id="@+id/drawer_layout_content"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:textSize="20dp"
                android:text="This is activity content area."/>

        </LinearLayout>

        <!-- Drawer menu component. -->
        <ListView
            android:id="@+id/drawer_layout_menu_list_view"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="start"
            android:choiceMode="singleChoice"/>

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

Below is the xml definition file for drawer ListView menu item.

activity_drawer_layout_menu_item.xml 

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

    <!-- Drawer ListView's item layout xml.-->
    <RelativeLayout
        android:id="@+id/drawer_layout_menu_item"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <ImageView
            android:id="@+id/drawer_layout_menu_item_image"
            android:layout_width="wrap_content"
            android:layout_height="fill_parent"
            android:layout_alignParentTop="true"
            android:layout_alignParentBottom="true"/>

        <TextView
            android:id="@+id/drawer_layout_menu_item_title"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textSize="20dp"
            android:textStyle="bold"
            android:layout_alignParentTop="true"
            android:layout_toRightOf="@id/drawer_layout_menu_item_image" />

    </RelativeLayout>

</LinearLayout>

All above xml file will be saved in app / res / layout folder.

READ :   Android DatePickerDialog TimePickerDialog Spinner Example

2. Drawer Layout Example.

2.1 Main Activity.

In this activity onCreate() method, it will use all above xml file to create the example, add drawer menu item etc.

DrawerLayoutActivity.java

package com.dev2qa.example.material_design;

import android.graphics.Color;
import android.os.Bundle;
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 android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.dev2qa.example.R;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class DrawerLayoutActivity extends AppCompatActivity {

    private DrawerLayout drawerLayout = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_drawer_layout);

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

        // Get drawer layout object.
        drawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout_widget);

        // Get user defined toolbar.
        Toolbar toolbar = (Toolbar)findViewById(R.id.drawer_layout_toolbar);
        setSupportActionBar(toolbar);

        // Get just configured toolbar.
        ActionBar actionBar = getSupportActionBar();
        if(actionBar != null)
        {
            // Show home icon at toolbar beginning..
            actionBar.setDisplayHomeAsUpEnabled(true);

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

        initializeDrawerMenuItems();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int menuItemId = item.getItemId();

        // If user click home button, the drawer menu will slide out.
        if(menuItemId == android.R.id.home)
        {
            drawerLayout.openDrawer(GravityCompat.START);
        }
        return super.onOptionsItemSelected(item);
    }

    /* This method add a ListView as drawer menu.*/
    private void initializeDrawerMenuItems()
    {
        // Menu item title array.
        String[] menuItemTitleArr = { "Java", "Android", "Selenium", "Junit","J2EE"};

        // Create list view item data.
        ArrayList<Map<String,Object>> itemDataList = new ArrayList<Map<String,Object>>();;

        int titleLen = menuItemTitleArr.length;
        for(int i =0; i < titleLen; i++) {
            Map<String,Object> listItemMap = new HashMap<String,Object>();
            listItemMap.put("imageId", R.mipmap.ic_launcher);
            listItemMap.put("itemTitle", menuItemTitleArr[i]);
            itemDataList.add(listItemMap);
        }

        // Create simple adapter to map list data to listview item layout component id.
        SimpleAdapter simpleAdapter = new SimpleAdapter(this,itemDataList,R.layout.activity_drawer_layout_menu_item,
                new String[]{"imageId","itemTitle"},new int[]{R.id.drawer_layout_menu_item_image, R.id.drawer_layout_menu_item_title});

        // Get ListView object.
        ListView menuListView = (ListView)findViewById(R.id.drawer_layout_menu_list_view);

        // Set custom simple adapter.
        menuListView.setAdapter(simpleAdapter);

        // Set listview background color.
        menuListView.setBackgroundColor(Color.WHITE);

        // When list view item is clicked.
        menuListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int index, long l) {

                // Get clicked menu item title.
                Object clickItemObj = adapterView.getAdapter().getItem(index);
                HashMap clickItemMap = (HashMap)clickItemObj;
                String itemTitle = (String)clickItemMap.get("itemTitle");

                // Set menu item title in screen content area.
                TextView contentTextView = (TextView)findViewById(R.id.drawer_layout_content);
                contentTextView.setText("You click drawer menu item " + itemTitle);

                // Close the drawer slide out menu.
                drawerLayout.closeDrawers();
            }
        });
    }
}

2.2 Android Manifest Xml File.

Please note because this example use android.support.v7.widget.Toolbar replace activity action bar, so you need set NoActionBar theme to the activity.

READ :   How To Create Android Custom Content Provider Example

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.DrawerLayoutActivity"
            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 Material Design Toolbar Example
(Visited 314 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.