Home Coding Android Coding Adding a Navigation Drawer in Android Studio

Adding a Navigation Drawer in Android Studio

0

navigation_drawer

With the latest component updates in Android, it is very easy to add a navigation drawer to your app. By default, users can slide it into view from the side. The latest version of Android Studio already includes a project template for an app that makes use of a navigation drawer, but for learning purposes, we’ll start to build a navigation drawer from scratch. To simplify things, we are also going to include a toggle switch in the action bar, so the users have multiple ways of interacting with our navigation drawer.

How to Create a Navigation Drawer in Android Studio

1. Create a New Android Studio project.

2. Leave the default minimum SDK.

3. Select an Empty Activity.

4. Insert the following dependencies into build.gradle:

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:21.0.3'
}

5.  Insert this code in activity_main.xml:

<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <!-- The first child in the layout is for the main Activity UI-->
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        android:paddingBottom="@dimen/activity_vertical_margin"
        tools:context=".MainActivity"
        android:background="#ffffffff">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:text="AppDosh.com Navigation Drawer"
            android:textSize="24sp"
            android:gravity="center"
            android:layout_marginTop="100dp"/>

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/appdosh"
            android:layout_marginBottom="73dp"
            android:layout_alignParentBottom="true"
            android:layout_centerHorizontal="true"/>

    </RelativeLayout>

    <!-- Navigation drawer UI -->
    <ListView
        android:id="@+id/navList"
        android:layout_width="200dp"
        android:layout_height="match_parent"
        android:layout_gravity="left|start"
        android:background="#ffeeeeee"/>

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

6. Now lets set up MainActivity.java:

package com.appdosh.navdrawer;

import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBarDrawerToggle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;


public class MainActivity extends ActionBarActivity {

    private ListView mDrawerList;
    private DrawerLayout mDrawerLayout;
    private ArrayAdapter<String> mAdapter;
    private ActionBarDrawerToggle mDrawerToggle;
    private String mActivityTitle;

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

        mDrawerList = (ListView)findViewById(R.id.navList);mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
        mActivityTitle = getTitle().toString();

        addDrawerItems();
        setupDrawer();

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);
    }

    private void addDrawerItems() {
        String[] osArray = { "Coding", "Reskinning", "Design", "Dev Guides", "Monetizations", "Reviews", "Marketing" };
        mAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, osArray);
        mDrawerList.setAdapter(mAdapter);

        mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Toast.makeText(MainActivity.this, "Visit www.appdosh.com !", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void setupDrawer() {
        mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.drawer_open, R.string.drawer_close) {

            /** This is called when the drawer has reached an open state */
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
                getSupportActionBar().setTitle("AppDosh Tabs");
                invalidateOptionsMenu();
            }

            /** This is called when the drawer is in a closed state */
            public void onDrawerClosed(View view) {
                super.onDrawerClosed(view);
                getSupportActionBar().setTitle(mActivityTitle);
                invalidateOptionsMenu();
            }
        };

        mDrawerToggle.setDrawerIndicatorEnabled(true);
        mDrawerLayout.setDrawerListener(mDrawerToggle);
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        mDrawerToggle.syncState();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        mDrawerToggle.onConfigurationChanged(newConfig);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflates the menu and ads item to the action bar
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // This action bar will handle clicks from the home button if you insert
        // the activity in AndroidManifest.xml
        int id = item.getItemId();

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

        // Navigation drawer toogle
        if (mDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

7. This is what our AndroidManifest.xml and strings.xml files looked like:

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

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.appdosh.navdrawer.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

</manifest>
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">Nav Drawer</string>
    <string name="hello_world">Hello readers!</string>
    <string name="action_settings">www.appdosh.com</string>
    <string name="drawer_open">Open navigation drawer</string>
    <string name="drawer_close">Close navigation drawer</string>

</resources>

8. This is what the end result would look like:

Denis Madroane App junkie, Android developer, proud Freelancer. Passionate about app development and blogging, updated with the new stuff. Likes to think that he's versed in app re-skinning, content writing and social media.

LEAVE YOUR COMMENT

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

Powered by WordPress