Skip to main content

Navigation Drawer sample source Code in Android Studio




activity_main.xml


<?xml version="1.0" encoding="utf-8"?>
<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"
    tools:context="com.example.johnwick.navigation_drawer.MainActivity">


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

    <ListView
        android:id="@+id/left_drawer"
        android:layout_width="240dp"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:background="#ACC"
        android:choiceMode="singleChoice"
        android:divider="#FFC7CCCC"
        android:dividerHeight="1dp"/>

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


strings.xml



<resources>
    <string name="app_name">Navigation_Drawer</string>
    <string-array name="navigation_drawer_items_array">
        <item>Home</item>
        <item>My Account</item>
        <item>Add User</item>
    </string-array>

    <string name="drawer_open">Open navigation drawer</string>
    <string name="drawer_close">Close navigation drawer</string>
</resources>



Now Create a Data Model class to pass data through listview:


ObjectDrawerItem.java


package com.example.johnwick.navigation_drawer;

/**
 * Created by John wick on 2/4/2016.
 */
public class ObjectDrawerItem {

    public String name;

    public ObjectDrawerItem(String name){
        this.name = name;
    }
}



Let's create an Adapter class for providing data to ListView:



DrawerItemCustomAdapter.java



package com.example.johnwick.navigation_drawer;

import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import java.util.ArrayList;

/**
 * Created by John wick on 2/4/2016.
 */
public class DrawerItemCustomAdapter extends ArrayAdapter<ObjectDrawerItem> {

   Context context;
    int layouResourceId;
    ObjectDrawerItem data[] = null;
    public DrawerItemCustomAdapter(Context context, int layoutResourceId, ObjectDrawerItem[] data) {
        super(context, layoutResourceId,data);
        this.layouResourceId = layoutResourceId;
        this.context = context;
        this.data = data;

    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        View listItem =  convertView;

        LayoutInflater inflater = ((Activity)context).getLayoutInflater();
        listItem = inflater.inflate(layouResourceId,parent,false);

        TextView textViewName = (TextView)listItem.findViewById(R.id.texViewName);

        ObjectDrawerItem folder = data[position];

        textViewName.setText(folder.name);

        return listItem;

    }
}


Coding for MainActivity.java class

MainActivity.java


package com.example.johnwick.navigation_drawer;

import android.app.Fragment;
import android.app.FragmentManager;
import android.support.annotation.Nullable;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

public class MainActivity extends AppCompatActivity {



    private String[] NavigationDrawerItemTitles;
    private DrawerLayout drawerLayout;
    private ListView listView;
    ActionBarDrawerToggle drawerToggle;
    private CharSequence mDrawerTitle;
    private CharSequence mTitle;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mTitle = mDrawerTitle = getTitle();


        NavigationDrawerItemTitles = getResources().getStringArray(R.array.navigation_drawer_items_array);
        drawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
        listView = (ListView)findViewById(R.id.left_drawer);

        drawerToggle = new ActionBarDrawerToggle( this,
                drawerLayout,
                R.string.drawer_open,
                R.string.drawer_close){

            public void onDrawerClosed(View view){
                super.onDrawerClosed(view);
                getSupportActionBar().setTitle(mTitle);
            }

            public void  onDrawerOpened(View drawerview){
                super.onDrawerOpened(drawerview);
                getSupportActionBar().setTitle(mDrawerTitle);
            }
        };

        drawerLayout.setDrawerListener(drawerToggle);

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


        ObjectDrawerItem[] drawerItems = new ObjectDrawerItem[3];

        drawerItems[0] =  new ObjectDrawerItem("Home");
        drawerItems[1] = new ObjectDrawerItem("My Account");
        drawerItems[2] = new ObjectDrawerItem("Add User");


        DrawerItemCustomAdapter adapter = new DrawerItemCustomAdapter(this,R.layout.listview_iten_row,drawerItems);

        listView.setAdapter(adapter);

        listView.setOnItemClickListener(new DrawerItemClickListener());

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        if(drawerToggle.onOptionsItemSelected(item)){
            return true;
        }
        return super.onOptionsItemSelected(item);

    }


    @Override
    public void setTitle(CharSequence title) {
        mTitle = title;
        getSupportActionBar().setTitle(mTitle);
    }

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

    public class DrawerItemClickListener implements ListView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            selectItem(position);
        }
    }

    private void selectItem(int position){

        Fragment fragment = null;

        switch (position){
            case 0:
                fragment = new HomeFragment();
                break;
            case 1:
                fragment =  new MyAccountFragment();
                break;
            case 2:
                fragment = new AddUserFragment();
                break;
            default:
                break;
        }

        if(fragment != null){

            FragmentManager fragmentManager = getFragmentManager();
            fragmentManager.beginTransaction().replace(R.id.content_frame,fragment).commit();

            listView.setItemChecked(position,true);
            listView.setSelection(position);
            setTitle(NavigationDrawerItemTitles[position]);
            drawerLayout.closeDrawer(listView);
        }
        else{
            Log.e("MainActiviy","Error in creating fragment");
        }


    }




}


Now Only thing we need to do is to create fragments for different listview items, below is sample code for one fragment likewise you can create the rest of the fragments:

xml for Fragment: 


fragment_home.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">


    <TextView
        android:id="@+id/txtLabel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="Home View"
        android:textSize="16dp" />
</LinearLayout>

Java file for fragment:


HomeFragment .java


package com.example.johnwick.navigation_drawer;

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

/**
 * Created by John wick on 2/4/2016.
 */
public class HomeFragment extends Fragment {

    public HomeFragment(){

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.fragment_home,container,false);
        return rootView;
    }
}


This is all you need to create a navigation drawer in android. Download the Source code and apk file from the below given links:

DownLoad: Source_Code
Apk file: apk_navigation_drawer












Comments

  1. Awesome article, also, if you want to get Tamilrockers new domains list then here is the best guide for you, so why you're waiting for click and read this.

    ReplyDelete

Post a Comment

Popular posts from this blog

Android: Login Screen using Fragments

In this tutorial, our focus is on making a User/Member login activity using fragments. With the help of Fragments we will use the same activity to show User login area and also Members Login area. Prerequisite for this tutorial: You should be know how to make an Activity And most importantly you should have prior Knowledge of Fragments. For practising basic Fragment implementation refer to Android Simple Fragment Example      We have used only three activities for this: MainActivity(which represents the Login Screen) Fragments for Members area Fragment for New Users

Simple Login/Register Example using SQLite database

MainActivity.java(login Screen) package com.AndroidDevelopmentGuru.database_new; import java.util.List; import android.app.Activity; import android.content.Intent; import android.database.Cursor; import android.os.Bundle; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class MainActivity extends Activity {                                 EditText user, pass;                 Button login, not_reg;                 DatabaseHandler db;           ...

Android: How to Generate Key Hash for Facebook Integration

Hello everyone, As this is a quite confusing for everyone to generate the key hash in your PC, so i decided to write about it. I have also tried many ways but every time i failed to generate the key hash. After trying for an hour i successfully generated the key. Just follow the below given Steps and you are done with this. Step I: Download Openssl from   here Step II: Download openssl-0.9.8e_X64.zip for 64 bit PC and openssl-0.9.8e_WIN32.zip for 32 bit PC Step III: once your download the zip folder. Go to C drive(where window is installed) and make a folder named openssl Step IV: extract all zip file in this folder. Step V: Now go to Java folder and copy path of jre. For example: C:\Program Files\Java\jre1.8.0_101\bin