You might have noticed that lot of android applications introduced a sliding panel menu to navigate between major modules of the application. Previously this kind of UI was done using some third party libraries where a list view and some swiping gestures used to achieve this. But now android itself officially introduced sliding panel menu by introducing a newer concept called Navigation Drawer in which we combine DrawerLayout and NavigationView to achieve the desired output.

Most of the time Sliding Menu (Navigation Drawer) will be hidden and can be shown by swiping the screen from left edge to right or tapping the app icon on the action bar.

android navigation drawer slider menu

Example Applications

You can see lot of popular applications like Facebook, Youtube, Google + already introduced navigation drawer menu in their applications. Following are the navigation drawer menus of multiple apps.

android navigation drawer facebook, google plus, youtube

1. Android Studio Navigation Drawer Template

You can add Navigation Drawer in your app in two ways. The quick and easy way is choosing the Navigation Drawer Activity from Android Studio when the new project is created. This creates an empty project with navigation drawer added.

android-navigation-drawer-android-studio

This creates the below basic skeleton app with few navigation menu items.

android-navigation-drawer-activity

Even though Android Studio gives you basic Navigation Drawer Menu, making it fully functional takes some effort. The next steps explains how to customize the navigation drawer appearance by adding header image, profile image and other texts. You will also learn how to prepare and attach the other menu views by creating the fragments and loading them properly.

To give you full information about navigation drawer, instead of choosing the drawer temple, I am creating an empty project and add the navigation drawer by explaining every step is needed. So let’s get started.

Below is the final output we are going to achieve in this article.

android-navigation-drawer-menu

2. Starting new Project

1. Create a new project in Android Studio from File ⇒ New Project by filling the required details. When it prompts you to select the activity, choose Empty Activity and continue.

2. Open build.gradle located in app level and add below dependencies. I am adding Glide image library dependency. This is not needed for navigation drawer, but to load the profile image from url.

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:24.0.0-beta1'
    compile 'com.android.support:design:24.0.0-beta1'
    compile 'com.android.support:support-v4:24.0.0-beta1'

    // Glide image library
    compile 'com.github.bumptech.glide:glide:3.7.0'
}

3. Open strings.xml, dimens.xml, colors.xml located under res ⇒ values and add the below values.

<resources>
    <string name="app_name">Navigation Drawer</string>

    <string name="navigation_drawer_open">Open navigation drawer</string>
    <string name="navigation_drawer_close">Close navigation drawer</string>
    <string name="openDrawer">open_drawer</string>
    <string name="closeDrawer">close_drawer</string>

    <!-- Navigation Drawer menu labels -->
    <string name="nav_home">Home</string>
    <string name="nav_photos">Photos</string>
    <string name="nav_movies">Movies</string>
    <string name="nav_notifications">Notifications</string>
    <string name="nav_settings">Settings</string>
    <string name="nav_about_us">About Us</string>

    <!-- Toolbar titles when navigation menu item is selected -->
    <string-array name="nav_item_activity_titles">
        <item>Home</item>
        <item>Photos</item>
        <item>Movies</item>
        <item>Notifications</item>
        <item>Settings</item>
    </string-array>

    <string name="activity_title_about_us">About Us</string>
    <string name="activity_title_privacy_policy">Privacy Policy</string>
    <string name="action_clear_all">Clear All</string>
    <string name="action_logout">Logout</string>
    <string name="action_mark_all_read">Mark All as Read</string>
    <string name="privacy_policy">Privacy Policy</string>
</resources>
<resources>
    <!-- Default screen margins, per the Android Design guidelines. -->
    <dimen name="nav_header_vertical_spacing">16dp</dimen>
    <dimen name="nav_header_height">160dp</dimen>

    <!-- Default screen margins, per the Android Design guidelines. -->
    <dimen name="activity_horizontal_margin">16dp</dimen>
    <dimen name="activity_vertical_margin">16dp</dimen>
    <dimen name="fab_margin">16dp</dimen>
    <dimen name="profile_width">75dp</dimen>
    <dimen name="profile_height">75dp</dimen>
</resources>
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#d32f2f</color>
    <color name="colorPrimaryDark">#c72c2c</color>
    <color name="colorAccent">#FFFFFF</color>
</resources>

4. Download Home, Photos, Movies, Notifications, Settings icons from Material Icons and add them to your project’s res folder. These icons will be used as navigation menu item icons.

5. Under res ⇒ menu directory, create two menu xml files named notifications.xml and main.xml. These menus are used to render different toolbar overflow menus when the user switches between navigation drawer items.

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/action_mark_all_read"
        android:orderInCategory="100"
        android:title="@string/action_mark_all_read"
        app:showAsAction="never" />

    <item
        android:id="@+id/action_clear_notifications"
        android:orderInCategory="101"
        android:title="@string/action_clear_all"
        app:showAsAction="never" />
</menu>
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/action_logout"
        android:orderInCategory="100"
        android:title="@string/action_logout"
        app:showAsAction="never" />
</menu>

Creating Fragments & Activities

6. Create three packages named activity, fragment, other and move the MainActivity.java to activity package.

7. Create all the fragment classes needed for navigation menu. Overall I am creating five fragment classes. Right click on fragment package, New ⇒ Fragment ⇒ Fragment (Blank) and name it as HomeFragment.java. This fragment will be loaded always whenever user open the app.

Likewise create other fragment activities named PhotosFragment, MoviesFragment, NotificationsFragment and SettingsFragment.

8. In our navigation drawer menu, there are two other menu items, About Us and Privacy Policy. For these two we are gonna create activities instead of fragments. Create new two activities named AboutUsActivity.java and PrivacyPolicyActivity.java.

android-navigation-drawer-project-structure

9. Inside other package, create a class named CircleTransform.java This class is used to display the profile image in circular fashion.

package info.androidhive.navigationdrawer.other;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Paint;

import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool;
import com.bumptech.glide.load.resource.bitmap.BitmapTransformation;

/**
 * Created by Lincoln on 10/03/16.
 */
public class CircleTransform extends BitmapTransformation {
    public CircleTransform(Context context) {
        super(context);
    }

    @Override
    protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
        return circleCrop(pool, toTransform);
    }

    private static Bitmap circleCrop(BitmapPool pool, Bitmap source) {
        if (source == null) return null;

        int size = Math.min(source.getWidth(), source.getHeight());
        int x = (source.getWidth() - size) / 2;
        int y = (source.getHeight() - size) / 2;

        // TODO this could be acquired from the pool too
        Bitmap squared = Bitmap.createBitmap(source, x, y, size, size);

        Bitmap result = pool.get(size, size, Bitmap.Config.ARGB_8888);
        if (result == null) {
            result = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
        }

        Canvas canvas = new Canvas(result);
        Paint paint = new Paint();
        paint.setShader(new BitmapShader(squared, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP));
        paint.setAntiAlias(true);
        float r = size / 2f;
        canvas.drawCircle(r, r, r, paint);
        return result;
    }

    @Override
    public String getId() {
        return getClass().getName();
    }
}

10. Under res ⇒ drawable, create a file named bg_circle.xml. This provides circular background to view.

<?xml version="1.0" encoding="utf-8"?>
<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">

    <solid
        android:color="@color/colorPrimary"/>

    <size
        android:width="120dp"
        android:height="120dp"/>
</shape>

11. Under res layout folder, create a layout named menu_dot.xml. This layout is used to render dot next to notifications label.

android-navigation-drawer-action-view

Adding Navigation Drawer

12. Under res ⇒ menu directory, create a menu xml file named activity_main_drawer.xml. This menu renders the Navigation Drawer list items. Here we set the icons and labels. You can also notice here <group> is used to combine multiple items under single levels. An <item> also can be used group multiple child items with a title. This provides a horizontal separator between the two sets.

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

    <group android:checkableBehavior="single">
        <item
            android:id="@+id/nav_home"
            android:icon="@drawable/ic_home_black_24dp"
            android:title="@string/nav_home" />
        <item
            android:id="@+id/nav_photos"
            android:icon="@drawable/ic_photo_library_black_24dp"
            android:title="@string/nav_photos" />
        <item
            android:id="@+id/nav_movies"
            android:icon="@drawable/ic_local_movies_black_24dp"
            android:title="@string/nav_movies" />

        <item
            android:id="@+id/nav_notifications"
            android:icon="@drawable/ic_notifications_black_24dp"
            android:title="@string/nav_notifications" />

        <item
            android:id="@+id/nav_settings"
            android:icon="@drawable/ic_settings_black_24dp"
            android:title="@string/nav_settings" />
    </group>

    <item android:title="Other">
        <menu>
            <item
                android:id="@+id/nav_about_us"
                android:title="@string/nav_about_us" />
            <item
                android:id="@+id/nav_privacy_policy"
                android:title="@string/privacy_policy" />
        </menu>
    </item>

</menu>

13. Under res ⇒ layout, create a file named nav_header_main.xml This layout renders the navigation drawer header part with a profile image, name and website.

14. Now we’ll create another layout file to add required Toolbar, FAB and FrameLayout. FrameLayout is used to load appropriate fragment when an item is selected from nav menu. Create a layout file named app_bar_main.xml under res ⇒ layout.

<?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"
    android:fitsSystemWindows="true"
    tools:context="info.androidhive.navigationdrawer.activity.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>

    <FrameLayout
        android:id="@+id/frame"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"></FrameLayout>

    <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:backgroundTint="@color/colorPrimary"
        app:srcCompat="@android:drawable/ic_dialog_email" />

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

15. Open the layout file your main activity activity_main.xml and add NavigationView element. You can notice that the toolbar layout is added using <include> tag.

<?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>

16. Now we have all the required elements in place. It’s time to open the main activity and do the necessary changes to make the navigation drawer functional. Open MainActivity.java and modify as explained below.

setUpNavigationView() – Initializes the Navigation Drawer by creating necessary click listeners and other functions.

loadNavHeader() – Function loads the navigation drawer header information like profile image, name and website. Here we use Glide image library to load the profile image.

getHomeFragment() – Returns the appropriate Fragment depending on the nav menu item user selected. For example if user selects Photos from nav menu, it returns PhotosFragment. This can be done by using the variable navItemIndex.

loadHomeFragment() – Loads the fragment returned from getHomeFragment() function into FrameLayout. It also takes care of other things like changing the toolbar title, hiding / showing fab, invalidating the options menu so that new menu can be loaded for different fragment.

Other code is very easy to understand and self explanatory. I have also added comments to each code block for better understanding.

package info.androidhive.navigationdrawer.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
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 android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;

import info.androidhive.navigationdrawer.R;
import info.androidhive.navigationdrawer.fragment.HomeFragment;
import info.androidhive.navigationdrawer.fragment.MoviesFragment;
import info.androidhive.navigationdrawer.fragment.NotificationsFragment;
import info.androidhive.navigationdrawer.fragment.PhotosFragment;
import info.androidhive.navigationdrawer.fragment.SettingsFragment;
import info.androidhive.navigationdrawer.other.CircleTransform;

public class MainActivity extends AppCompatActivity {

    private NavigationView navigationView;
    private DrawerLayout drawer;
    private View navHeader;
    private ImageView imgNavHeaderBg, imgProfile;
    private TextView txtName, txtWebsite;
    private Toolbar toolbar;
    private FloatingActionButton fab;

    // urls to load navigation header background image
    // and profile image
    private static final String urlNavHeaderBg = "https://api.androidhive.info/images/nav-menu-header-bg.jpg";
    private static final String urlProfileImg = "https://lh3.googleusercontent.com/eCtE_G34M9ygdkmOpYvCag1vBARCmZwnVS6rS5t4JLzJ6QgQSBquM0nuTsCpLhYbKljoyS-txg";

    // index to identify current nav menu item
    public static int navItemIndex = 0;

    // tags used to attach the fragments
    private static final String TAG_HOME = "home";
    private static final String TAG_PHOTOS = "photos";
    private static final String TAG_MOVIES = "movies";
    private static final String TAG_NOTIFICATIONS = "notifications";
    private static final String TAG_SETTINGS = "settings";
    public static String CURRENT_TAG = TAG_HOME;

    // toolbar titles respected to selected nav menu item
    private String[] activityTitles;

    // flag to load home fragment when user presses back key
    private boolean shouldLoadHomeFragOnBackPress = true;
    private Handler mHandler;


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

        mHandler = new Handler();

        drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        navigationView = (NavigationView) findViewById(R.id.nav_view);
        fab = (FloatingActionButton) findViewById(R.id.fab);

        // Navigation view header
        navHeader = navigationView.getHeaderView(0);
        txtName = (TextView) navHeader.findViewById(R.id.name);
        txtWebsite = (TextView) navHeader.findViewById(R.id.website);
        imgNavHeaderBg = (ImageView) navHeader.findViewById(R.id.img_header_bg);
        imgProfile = (ImageView) navHeader.findViewById(R.id.img_profile);

        // load toolbar titles from string resources
        activityTitles = getResources().getStringArray(R.array.nav_item_activity_titles);

        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();
            }
        });

        // load nav menu header data
        loadNavHeader();

        // initializing navigation menu
        setUpNavigationView();

        if (savedInstanceState == null) {
            navItemIndex = 0;
            CURRENT_TAG = TAG_HOME;
            loadHomeFragment();
        }
    }

    /***
     * Load navigation menu header information
     * like background image, profile image
     * name, website, notifications action view (dot)
     */
    private void loadNavHeader() {
        // name, website
        txtName.setText("Ravi Tamada");
        txtWebsite.setText("www.androidhive.info");

        // loading header background image
        Glide.with(this).load(urlNavHeaderBg)
                .crossFade()
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .into(imgNavHeaderBg);

        // Loading profile image
        Glide.with(this).load(urlProfileImg)
                .crossFade()
                .thumbnail(0.5f)
                .bitmapTransform(new CircleTransform(this))
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .into(imgProfile);

        // showing dot next to notifications label
        navigationView.getMenu().getItem(3).setActionView(R.layout.menu_dot);
    }

    /***
     * Returns respected fragment that user
     * selected from navigation menu
     */
    private void loadHomeFragment() {
        // selecting appropriate nav menu item
        selectNavMenu();

        // set toolbar title
        setToolbarTitle();

        // if user select the current navigation menu again, don't do anything
        // just close the navigation drawer
        if (getSupportFragmentManager().findFragmentByTag(CURRENT_TAG) != null) {
            drawer.closeDrawers();

            // show or hide the fab button
            toggleFab();
            return;
        }

        // Sometimes, when fragment has huge data, screen seems hanging
        // when switching between navigation menus
        // So using runnable, the fragment is loaded with cross fade effect
        // This effect can be seen in GMail app
        Runnable mPendingRunnable = new Runnable() {
            @Override
            public void run() {
                // update the main content by replacing fragments
                Fragment fragment = getHomeFragment();
                FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
                fragmentTransaction.setCustomAnimations(android.R.anim.fade_in,
                        android.R.anim.fade_out);
                fragmentTransaction.replace(R.id.frame, fragment, CURRENT_TAG);
                fragmentTransaction.commitAllowingStateLoss();
            }
        };

        // If mPendingRunnable is not null, then add to the message queue
        if (mPendingRunnable != null) {
            mHandler.post(mPendingRunnable);
        }

        // show or hide the fab button
        toggleFab();

        //Closing drawer on item click
        drawer.closeDrawers();

        // refresh toolbar menu
        invalidateOptionsMenu();
    }

    private Fragment getHomeFragment() {
        switch (navItemIndex) {
            case 0:
                // home
                HomeFragment homeFragment = new HomeFragment();
                return homeFragment;
            case 1:
                // photos
                PhotosFragment photosFragment = new PhotosFragment();
                return photosFragment;
            case 2:
                // movies fragment
                MoviesFragment moviesFragment = new MoviesFragment();
                return moviesFragment;
            case 3:
                // notifications fragment
                NotificationsFragment notificationsFragment = new NotificationsFragment();
                return notificationsFragment;

            case 4:
                // settings fragment
                SettingsFragment settingsFragment = new SettingsFragment();
                return settingsFragment;
            default:
                return new HomeFragment();
        }
    }

    private void setToolbarTitle() {
        getSupportActionBar().setTitle(activityTitles[navItemIndex]);
    }

    private void selectNavMenu() {
        navigationView.getMenu().getItem(navItemIndex).setChecked(true);
    }

    private void setUpNavigationView() {
        //Setting Navigation View Item Selected Listener to handle the item click of the navigation menu
        navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {

            // This method will trigger on item Click of navigation menu
            @Override
            public boolean onNavigationItemSelected(MenuItem menuItem) {

                //Check to see which item was being clicked and perform appropriate action
                switch (menuItem.getItemId()) {
                    //Replacing the main content with ContentFragment Which is our Inbox View;
                    case R.id.nav_home:
                        navItemIndex = 0;
                        CURRENT_TAG = TAG_HOME;
                        break;
                    case R.id.nav_photos:
                        navItemIndex = 1;
                        CURRENT_TAG = TAG_PHOTOS;
                        break;
                    case R.id.nav_movies:
                        navItemIndex = 2;
                        CURRENT_TAG = TAG_MOVIES;
                        break;
                    case R.id.nav_notifications:
                        navItemIndex = 3;
                        CURRENT_TAG = TAG_NOTIFICATIONS;
                        break;
                    case R.id.nav_settings:
                        navItemIndex = 4;
                        CURRENT_TAG = TAG_SETTINGS;
                        break;
                    case R.id.nav_about_us:
                        // launch new intent instead of loading fragment
                        startActivity(new Intent(MainActivity.this, AboutUsActivity.class));
                        drawer.closeDrawers();
                        return true;
                    case R.id.nav_privacy_policy:
                        // launch new intent instead of loading fragment
                        startActivity(new Intent(MainActivity.this, PrivacyPolicyActivity.class));
                        drawer.closeDrawers();
                        return true;
                    default:
                        navItemIndex = 0;
                }

                //Checking if the item is in checked state or not, if not make it in checked state
                if (menuItem.isChecked()) {
                    menuItem.setChecked(false);
                } else {
                    menuItem.setChecked(true);
                }
                menuItem.setChecked(true);

                loadHomeFragment();

                return true;
            }
        });


        ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.openDrawer, R.string.closeDrawer) {

            @Override
            public void onDrawerClosed(View drawerView) {
                // Code here will be triggered once the drawer closes as we dont want anything to happen so we leave this blank
                super.onDrawerClosed(drawerView);
            }

            @Override
            public void onDrawerOpened(View drawerView) {
                // Code here will be triggered once the drawer open as we dont want anything to happen so we leave this blank
                super.onDrawerOpened(drawerView);
            }
        };

        //Setting the actionbarToggle to drawer layout
        drawer.setDrawerListener(actionBarDrawerToggle);

        //calling sync state is necessary or else your hamburger icon wont show up
        actionBarDrawerToggle.syncState();
    }

    @Override
    public void onBackPressed() {
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawers();
            return;
        }

        // This code loads home fragment when back key is pressed
        // when user is in other fragment than home
        if (shouldLoadHomeFragOnBackPress) {
            // checking if user is on other navigation menu
            // rather than home
            if (navItemIndex != 0) {
                navItemIndex = 0;
                CURRENT_TAG = TAG_HOME;
                loadHomeFragment();
                return;
            }
        }

        super.onBackPressed();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.

        // show menu only when home fragment is selected
        if (navItemIndex == 0) {
            getMenuInflater().inflate(R.menu.main, menu);
        }

        // when fragment is notifications, load the menu created for notifications
        if (navItemIndex == 3) {
            getMenuInflater().inflate(R.menu.notifications, 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_logout) {
            Toast.makeText(getApplicationContext(), "Logout user!", Toast.LENGTH_LONG).show();
            return true;
        }

        // user is in notifications fragment
        // and selected 'Mark all as Read'
        if (id == R.id.action_mark_all_read) {
            Toast.makeText(getApplicationContext(), "All notifications marked as read!", Toast.LENGTH_LONG).show();
        }

        // user is in notifications fragment
        // and selected 'Clear All'
        if (id == R.id.action_clear_notifications) {
            Toast.makeText(getApplicationContext(), "Clear all notifications!", Toast.LENGTH_LONG).show();
        }

        return super.onOptionsItemSelected(item);
    }

    // show or hide the fab
    private void toggleFab() {
        if (navItemIndex == 0)
            fab.show();
        else
            fab.hide();
    }
}

Run and test the app once. You should able to see the app as shown below. Also check the Video demo of fully implemented navigation drawer.

android-navigation-drawer-menu
Ravi is hardcore Android programmer and Android programming has been his passion since he compiled his first hello-world program. Solving real problems of Android developers through tutorials has always been interesting part for him.
  • Mamro Kirill

    Perfect example. Thank you.
    And how to make a more sophisticated style of a picture in G+ for example?

    • You mean to change it to white color or adding an image above listview ?

      • Gaurav Mahajan

        how can we change the g+ icon?

        • Gaurav Mahajan

          I think, its same as application icon. ic_launcher.png

          • Yes

          • Salman Shah

            hey Ravi Please tell us about header??

          • prabhakar

            Hello Ravi,

            I am trying to implement this code but Activity not started

            the logcat show following error

            07-26 06:13:41.167: E/AndroidRuntime(2219): FATAL EXCEPTION: main

            07-26 06:13:41.167: E/AndroidRuntime(2219): Process: com.easy.menu, PID: 2219

            07-26 06:13:41.167: E/AndroidRuntime(2219): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.easy.menu/com.easy.menu.MainActivity}: android.view.InflateException: Binary XML file line #14: Error inflating class android.widget.ListView

            07-26 06:13:41.167: E/AndroidRuntime(2219): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)

            07-26 06:13:41.167: E/AndroidRuntime(2219): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)

            07-26 06:13:41.167: E/AndroidRuntime(2219): at android.app.ActivityThread.access$800(ActivityThread.java:135)

            07-26 06:13:41.167: E/AndroidRuntime(2219): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)

            07-26 06:13:41.167: E/AndroidRuntime(2219): at android.os.Handler.dispatchMessage(Handler.java:102)

            07-26 06:13:41.167: E/AndroidRuntime(2219): at android.os.Looper.loop(Looper.java:136)

            07-26 06:13:41.167: E/AndroidRuntime(2219): at android.app.ActivityThread.main(ActivityThread.java:5017)

            07-26 06:13:41.167: E/AndroidRuntime(2219): at java.lang.reflect.Method.invokeNative(Native Method)

            07-26 06:13:41.167: E/AndroidRuntime(2219): at java.lang.reflect.Method.invoke(Method.java:515)

            07-26 06:13:41.167: E/AndroidRuntime(2219): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)

            07-26 06:13:41.167: E/AndroidRuntime(2219): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)

            07-26 06:13:41.167: E/AndroidRuntime(2219): at dalvik.system.NativeStart.main(Native Method)

            07-26 06:13:41.167: E/AndroidRuntime(2219): Caused by: android.view.InflateException: Binary XML file line #14: Error inflating class android.widget.ListView

            07-26 06:13:41.167: E/AndroidRuntime(2219): at android.view.LayoutInflater.createView(LayoutInflater.java:620)

            07-26 06:13:41.167: E/AndroidRuntime(2219): at com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:56)

            07-26 06:13:41.167: E/AndroidRuntime(2219): at android.view.LayoutInflater.onCreateView(LayoutInflater.java:669)

            07-26 06:13:41.167: E/AndroidRuntime(2219): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:694)

            07-26 06:13:41.167: E/AndroidRuntime(2219): at android.view.LayoutInflater.rInflate(LayoutInflater.java:755)

            07-26 06:13:41.167: E/AndroidRuntime(2219): at android.view.LayoutInflater.inflate(LayoutInflater.java:492)

            07-26 06:13:41.167: E/AndroidRuntime(2219): at android.view.LayoutInflater.inflate(LayoutInflater.java:397)

            07-26 06:13:41.167: E/AndroidRuntime(2219): at android.view.LayoutInflater.inflate(LayoutInflater.java:353)

            07-26 06:13:41.167: E/AndroidRuntime(2219): at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:290)

            07-26 06:13:41.167: E/AndroidRuntime(2219): at android.app.Activity.setContentView(Activity.java:1929)

            07-26 06:13:41.167: E/AndroidRuntime(2219): at com.easy.menu.MainActivity.onCreate(MainActivity.java:46)

            07-26 06:13:41.167: E/AndroidRuntime(2219): at android.app.Activity.performCreate(Activity.java:5231)

            07-26 06:13:41.167: E/AndroidRuntime(2219): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)

            07-26 06:13:41.167: E/AndroidRuntime(2219): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)

            07-26 06:13:41.167: E/AndroidRuntime(2219): … 11 more

            07-26 06:13:41.167: E/AndroidRuntime(2219): Caused by: java.lang.reflect.InvocationTargetException

            07-26 06:13:41.167: E/AndroidRuntime(2219): at java.lang.reflect.Constructor.constructNative(Native Method)

            07-26 06:13:41.167: E/AndroidRuntime(2219): at java.lang.reflect.Constructor.newInstance(Constructor.java:423)

            07-26 06:13:41.167: E/AndroidRuntime(2219): at android.view.LayoutInflater.createView(LayoutInflater.java:594)

            07-26 06:13:41.167: E/AndroidRuntime(2219): … 24 more

            07-26 06:13:41.167: E/AndroidRuntime(2219): Caused by: android.content.res.Resources$NotFoundException: File res/color/primary_text_dark.xml from drawable resource ID #0x1060001

            07-26 06:13:41.167: E/AndroidRuntime(2219): at android.content.res.Resources.loadDrawable(Resources.java:2096)

            07-26 06:13:41.167: E/AndroidRuntime(2219): at android.content.res.TypedArray.getDrawable(TypedArray.java:602)

            07-26 06:13:41.167: E/AndroidRuntime(2219): at android.widget.ListView.(ListView.java:158)

            07-26 06:13:41.167: E/AndroidRuntime(2219): at android.widget.ListView.(ListView.java:142)

            07-26 06:13:41.167: E/AndroidRuntime(2219): … 27 more

            07-26 06:13:41.167: E/AndroidRuntime(2219): Caused by: org.xmlpull.v1.XmlPullParserException: Binary XML file line #18: tag requires a ‘drawable’ attribute or child tag defining a drawable

            07-26 06:13:41.167: E/AndroidRuntime(2219): at android.graphics.drawable.StateListDrawable.inflate(StateListDrawable.java:181)

            07-26 06:13:41.167: E/AndroidRuntime(2219): at android.graphics.drawable.Drawable.createFromXmlInner(Drawable.java:937)

            07-26 06:13:41.167: E/AndroidRuntime(2219): at android.graphics.drawable.Drawable.createFromXml(Drawable.java:877)

            07-26 06:13:41.167: E/AndroidRuntime(2219): at android.content.res.Resources.loadDrawable(Resources.java:2092)

            07-26 06:13:41.167: E/AndroidRuntime(2219): … 30 more

            please help how to solve this.
            Thank You:)

  • Thanks very much i need this tutorial to continue my application

    • You are welcome 🙂

      • i wana another tutorial if possible
        how to upload my picture from android to my Server with PHP
        Thanks man

        • I already prepared a project, but the problem is it is not uploading more than 2MB file. I am still figuring out the solution.

          • Thanks man
            I’m waiting this tutorial

          • Ravi, check that this 2MB restriction is not due to PHP’s configuration (ie. php.ini).

            (PS: I’ve sent you a tutorial request. I must hand a highschool project on december and a tutorial on SSH connections in Android apps would help me a lot!)

          • Hi Xaic,

            The problem is not on serverside. It is on client side. Getting memory exceptions …

          • Hi Ravi. In case you want the full image to be uploaded I don’t know how to help. However, if you don’t mind on the image resolution I propose reducing the image before sending it to the server.

          • Yeah, good suggestion in case of Image upload. But we need to consider the case of uploading video to server or some zip file.

  • Ramiz Mohamed

    Nice post, Ravi.

  • Yogesh

    Thank you for the post. It really helps you out. I just have one question, is there a way we can make it work with a custom sliding menu like https://github.com/jfeinstein10/SlidingMenu, can you just look into it.

    Thanks.

  • Mahmudul

    Nice post. Like it!!!

  • chandan

    This is one of the most awaited post.. Loved it 🙂

  • Anh Tuan

    Great. But how do it run on API 8 ( Android 2.2 ). Current Project is :
    android:minSdkVersion=”11″
    android:targetSdkVersion=”17″

  • Hue Nguyen

    First, thanks for your tutorial, I have tested your demo but there is an occasional error when dragging menu appears only a part and not the whole show Menu.

  • Gaurav Mahajan

    Thanks for posing this. very nice.

  • Radhakrishnan

    nice tutorial ..androidhive you rocks always

  • amay

    Hai ravi, i want run it on API 8 ( Android 2.2 ), i have using Support Library with add android-support-v4.jar in folder jar , in manifest i am change android:minSdkVersion=”8″ , but it still force close . how to fix it ?

    • Debug the errors and tell me what is the error you are getting. (Use Logcat to see the errors)

      • amay

        11-14 15:03:42.524: I/dalvikvm(299): Could not find method info.androidhive.slidingmenu.MainActivity.getFragmentManager, referenced from method info.androidhive.slidingmenu.MainActivity.displayView

        11-14 15:03:42.524: W/dalvikvm(299): VFY: unable to resolve virtual method 4636: Linfo/androidhive/slidingmenu/MainActivity;.getFragmentManager ()Landroid/app/FragmentManager;

        11-14 15:03:42.524: D/dalvikvm(299): VFY: replacing opcode 0x6e at 0x0006

        11-14 15:03:42.534: W/dalvikvm(299): Unable to resolve superclass of Linfo/androidhive/slidingmenu/HomeFragment; (12)

        11-14 15:03:42.534: W/dalvikvm(299): Link of class ‘Linfo/androidhive/slidingmenu/HomeFragment;’ failed

        11-14 15:03:42.534: E/dalvikvm(299): Could not find class ‘info.androidhive.slidingmenu.HomeFragment’, referenced from method info.androidhive.slidingmenu.MainActivity.displayView

        11-14 15:03:42.534: W/dalvikvm(299): VFY: unable to resolve new-instance 638 (Linfo/androidhive/slidingmenu/HomeFragment;) in Linfo/androidhive/slidingmenu/MainActivity;

        11-14 15:03:42.534: D/dalvikvm(299): VFY: replacing opcode 0x22 at 0x0032

        11-14 15:03:42.534: W/dalvikvm(299): Unable to resolve superclass of Linfo/androidhive/slidingmenu/FindPeopleFragment; (12)

        11-14 15:03:42.534: W/dalvikvm(299): Link of class ‘Linfo/androidhive/slidingmenu/FindPeopleFragment;’ failed

        11-14 15:03:42.534: E/dalvikvm(299): Could not find class ‘info.androidhive.slidingmenu.FindPeopleFragment’, referenced from method info.androidhive.slidingmenu.MainActivity.displayView

        11-14 15:03:42.534: W/dalvikvm(299): VFY: unable to resolve new-instance 637 (Linfo/androidhive/slidingmenu/FindPeopleFragment;) in Linfo/androidhive/slidingmenu/MainActivity;

        11-14 15:03:42.534: D/dalvikvm(299): VFY: replacing opcode 0x22 at 0x0038

        11-14 15:03:42.544: W/dalvikvm(299): Unable to resolve superclass of Linfo/androidhive/slidingmenu/PhotosFragment; (12)

        11-14 15:03:42.544: W/dalvikvm(299): Link of class ‘Linfo/androidhive/slidingmenu/PhotosFragment;’ failed

        11-14 15:03:42.544: E/dalvikvm(299): Could not find class ‘info.androidhive.slidingmenu.PhotosFragment’, referenced from method info.androidhive.slidingmenu.MainActivity.displayView

        11-14 15:03:42.544: W/dalvikvm(299): VFY: unable to resolve new-instance 643 (Linfo/androidhive/slidingmenu/PhotosFragment;) in Linfo/androidhive/slidingmenu/MainActivity;

        11-14 15:03:42.544: D/dalvikvm(299): VFY: replacing opcode 0x22 at 0x003e

        11-14 15:03:42.554: W/dalvikvm(299): Unable to resolve superclass of Linfo/androidhive/slidingmenu/CommunityFragment; (12)

        11-14 15:03:42.554: W/dalvikvm(299): Link of class ‘Linfo/androidhive/slidingmenu/CommunityFragment;’ failed

        11-14 15:03:42.554: E/dalvikvm(299): Could not find class ‘info.androidhive.slidingmenu.CommunityFragment’, referenced from method info.androidhive.slidingmenu.MainActivity.displayView

        11-14 15:03:42.564: W/dalvikvm(299): VFY: unable to resolve new-instance 636 (Linfo/androidhive/slidingmenu/CommunityFragment;) in Linfo/androidhive/slidingmenu/MainActivity;

        11-14 15:03:42.564: D/dalvikvm(299): VFY: replacing opcode 0x22 at 0x0044

        11-14 15:03:42.564: W/dalvikvm(299): Unable to resolve superclass of Linfo/androidhive/slidingmenu/PagesFragment; (12)

        11-14 15:03:42.564: W/dalvikvm(299): Link of class ‘Linfo/androidhive/slidingmenu/PagesFragment;’ failed

        11-14 15:03:42.574: E/dalvikvm(299): Could not find class ‘info.androidhive.slidingmenu.PagesFragment’, referenced from method info.androidhive.slidingmenu.MainActivity.displayView

        11-14 15:03:42.574: W/dalvikvm(299): VFY: unable to resolve new-instance 642 (Linfo/androidhive/slidingmenu/PagesFragment;) in Linfo/androidhive/slidingmenu/MainActivity;

        11-14 15:03:42.574: D/dalvikvm(299): VFY: replacing opcode 0x22 at 0x004a

        11-14 15:03:42.584: W/dalvikvm(299): Unable to resolve superclass of Linfo/androidhive/slidingmenu/WhatsHotFragment; (12)

        11-14 15:03:42.584: W/dalvikvm(299): Link of class ‘Linfo/androidhive/slidingmenu/WhatsHotFragment;’ failed

        11-14 15:03:42.584: E/dalvikvm(299): Could not find class ‘info.androidhive.slidingmenu.WhatsHotFragment’, referenced from method info.androidhive.slidingmenu.MainActivity.displayView

        11-14 15:03:42.584: W/dalvikvm(299): VFY: unable to resolve new-instance 655 (Linfo/androidhive/slidingmenu/WhatsHotFragment;) in Linfo/androidhive/slidingmenu/MainActivity;

        11-14 15:03:42.584: D/dalvikvm(299): VFY: replacing opcode 0x22 at 0x0050

        11-14 15:03:42.584: D/dalvikvm(299): VFY: dead code 0x0009-0030 in Linfo/androidhive/slidingmenu/MainActivity;.displayView (I)V

        11-14 15:03:42.584: D/dalvikvm(299): VFY: dead code 0x0034-0037 in Linfo/androidhive/slidingmenu/MainActivity;.displayView (I)V

        11-14 15:03:42.594: D/dalvikvm(299): VFY: dead code 0x003a-003d in Linfo/androidhive/slidingmenu/MainActivity;.displayView (I)V

        11-14 15:03:42.594: D/dalvikvm(299): VFY: dead code 0x0040-0043 in Linfo/androidhive/slidingmenu/MainActivity;.displayView (I)V

        11-14 15:03:42.594: D/dalvikvm(299): VFY: dead code 0x0046-0049 in Linfo/androidhive/slidingmenu/MainActivity;.displayView (I)V

        11-14 15:03:42.594: D/dalvikvm(299): VFY: dead code 0x004c-004f in Linfo/androidhive/slidingmenu/MainActivity;.displayView (I)V

        11-14 15:03:42.594: D/dalvikvm(299): VFY: dead code 0x0052-0055 in Linfo/androidhive/slidingmenu/MainActivity;.displayView (I)V

        11-14 15:03:42.614: I/dalvikvm(299): Could not find method info.androidhive.slidingmenu.MainActivity.getActionBar, referenced from method info.androidhive.slidingmenu.MainActivity.onCreate

        11-14 15:03:42.624: W/dalvikvm(299): VFY: unable to resolve virtual method 4634: Linfo/androidhive/slidingmenu/MainActivity;.getActionBar ()Landroid/app/ActionBar;

        11-14 15:03:42.624: D/dalvikvm(299): VFY: replacing opcode 0x6e at 0x00ee

        11-14 15:03:42.624: D/dalvikvm(299): VFY: dead code 0x00f1-011a in Linfo/androidhive/slidingmenu/MainActivity;.onCreate (Landroid/os/Bundle;)V

        11-14 15:03:42.634: I/dalvikvm(299): Could not find method info.androidhive.slidingmenu.MainActivity.getActionBar, referenced from method info.androidhive.slidingmenu.MainActivity.setTitle

        11-14 15:03:42.634: W/dalvikvm(299): VFY: unable to resolve virtual method 4634: Linfo/androidhive/slidingmenu/MainActivity;.getActionBar ()Landroid/app/ActionBar;

        11-14 15:03:42.634: D/dalvikvm(299): VFY: replacing opcode 0x6e at 0x0002

        11-14 15:03:42.634: D/dalvikvm(299): VFY: dead code 0x0005-000b in Linfo/androidhive/slidingmenu/MainActivity;.setTitle (Ljava/lang/CharSequence;)V

        11-14 15:03:42.764: D/AndroidRuntime(299): Shutting down VM

        11-14 15:03:42.764: W/dalvikvm(299): threadid=1: thread exiting with uncaught exception (group=0x4001d800)

        11-14 15:03:42.784: E/AndroidRuntime(299): FATAL EXCEPTION: main

        11-14 15:03:42.784: E/AndroidRuntime(299): java.lang.NoSuchMethodError: info.androidhive.slidingmenu.MainActivity.getActionBar

        11-14 15:03:42.784: E/AndroidRuntime(299): at info.androidhive.slidingmenu.MainActivity.onCreate(MainActivity.java:86)

        11-14 15:03:42.784: E/AndroidRuntime(299): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)

        11-14 15:03:42.784: E/AndroidRuntime(299): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)

        11-14 15:03:42.784: E/AndroidRuntime(299): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)

        11-14 15:03:42.784: E/AndroidRuntime(299): at android.app.ActivityThread.access$2300(ActivityThread.java:125)

        11-14 15:03:42.784: E/AndroidRuntime(299): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)

        11-14 15:03:42.784: E/AndroidRuntime(299): at android.os.Handler.dispatchMessage(Handler.java:99)

        11-14 15:03:42.784: E/AndroidRuntime(299): at android.os.Looper.loop(Looper.java:123)

        11-14 15:03:42.784: E/AndroidRuntime(299): at android.app.ActivityThread.main(ActivityThread.java:4627)

        11-14 15:03:42.784: E/AndroidRuntime(299): at java.lang.reflect.Method.invokeNative(Native Method)

        11-14 15:03:42.784: E/AndroidRuntime(299): at java.lang.reflect.Method.invoke(Method.java:521)

        11-14 15:03:42.784: E/AndroidRuntime(299): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)

        11-14 15:03:42.784: E/AndroidRuntime(299): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)

        11-14 15:03:42.784: E/AndroidRuntime(299): at dalvik.system.NativeStart.main(Native Method)

        • While using the Support Library you need to change lot of methods.

          Use getSupportFragmentManager() instead of getFragmentManager()

          Also use getSupportActionBar() you should use getActionBar()

  • imelyaa

    hy ravi. like the others , I still can’t run this project (Android 2.3) although I was using support Library , this is my logcat , thanks 🙂

    11-14 14:06:42.000: E/AndroidRuntime(22980): FATAL EXCEPTION: main

    11-14 14:06:42.000: E/AndroidRuntime(22980): java.lang.NoSuchMethodError: info.androidhive.slidingmenu.MainActivity.getActionBar

    11-14 14:06:42.000: E/AndroidRuntime(22980): at info.androidhive.slidingmenu.MainActivity.onCreate(MainActivity.java:87)

    11-14 14:06:42.000: E/AndroidRuntime(22980): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)

    11-14 14:06:42.000: E/AndroidRuntime(22980): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1615)

    11-14 14:06:42.000: E/AndroidRuntime(22980): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1667)

    11-14 14:06:42.000: E/AndroidRuntime(22980): at android.app.ActivityThread.access$1500(ActivityThread.java:117)

    11-14 14:06:42.000: E/AndroidRuntime(22980): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:935)

    11-14 14:06:42.000: E/AndroidRuntime(22980): at android.os.Handler.dispatchMessage(Handler.java:99)

    11-14 14:06:42.000: E/AndroidRuntime(22980): at android.os.Looper.loop(Looper.java:130)

    11-14 14:06:42.000: E/AndroidRuntime(22980): at android.app.ActivityThread.main(ActivityThread.java:3687)

    11-14 14:06:42.000: E/AndroidRuntime(22980): at java.lang.reflect.Method.invokeNative(Native Method)

    11-14 14:06:42.000: E/AndroidRuntime(22980): at java.lang.reflect.Method.invoke(Method.java:507)

    11-14 14:06:42.000: E/AndroidRuntime(22980): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)

    11-14 14:06:42.000: E/AndroidRuntime(22980): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)

    11-14 14:06:42.000: E/AndroidRuntime(22980): at dalvik.system.NativeStart.main(Native Method)

    • Hi Imelyaa,

      You are using support library, instead of calling getActionBar() you should use getSupportActionBar()

      • ranjithstar256

        ravi bro for me when i use getsupportActionBar() it is showing, the method getsupportActionBar() is definded for the type MainActivity… What should i do bro??

    • Firos

      sir, i need tutorial for simple chat app like whatsApp. pls help me.

    • ShahNawaz Khan

      2.3 doesn’t support actionbar, checkout actionbar sherlock library

  • Dennis Drzosga

    HI Ravi,
    it is possile to call a second sliding menu on the right side, if call for example the PhotosFragment to select a folder or something, if yes can you tell me how.

  • Ravi

    Hey Ravi,
    Thanks for this post… i was looking for this tutorial from a long time now finally got it from you but i am not able to run it on 2.3 when i change min and target sdk version to 7 and 19 respectively i get error and wont be able to run project ..please help me …..

    • Give me the error you are getting ?

      • Guest

        if i am compile with android api 17 and higher it is working fine but whenever i compile it with lower version i.e. on 2.3 i get exception(No such Method) on getactionbar() method in main activity

      • Ravi

        i am getting exception on getActionBar method (No Such Method).I am using support library but didn’t find any method like getSupportActionBar()

      • Ravi

        i have changed mainactivity extend to fragmentactivity instead of activity class but cant find method getsupprortactionbar . i am getting arror “aapt.exe” encountered a problem

    • javadroid

      i think you use android.fragment instead android.support.v4.fragment

      • Ravi

        but android.fragment doesn’t work on API lower than 11 i want it to compatible with on 2.1 and 2.3 too…

  • javadroid

    thanks Ravi,
    it was so useful 🙂

  • zeeshan

    great work Ravi, keep it up 🙂

  • EL Benderradji Kheireddine

    great job dude !

  • Sithu

    Thanks Ravi

  • Alexiel

    Many thanks for your good work!

  • Kittu

    Hey Ravi, great tutorial, I am looking for an expandable sliding menu, I have tried to implement an expandable listview in place of your basic listview but could not get the solution. Any help will be much appretiated

      • Kittu

        Yeh, the error says that an expandable listview is not allowed inside drawer layout

      • Salman Shah

        Hi Ravi Thanks for this Nice Tutorial..
        Now we have a problem to put header or title so to categorize the list…but we dont know how to do it….i spent a whole week on search on how to add header to this list view but failed…Some other guys also ask the same question before but you didn’t reply for that..please help us on how to add header to the list view in this source??
        Thanks once again for such a nice Tutorial

  • Trollzito

    Excelente i love you!! yeahhh!!! fuck

  • Sweet.Misery

    Guys…honestly you have the best tutorials over the internet. they were really usefull for me.
    I love U so much. wish you bests.

  • Ravi

    Please upload code which is compatible with 2.3 too. I will be thankful to you….

  • Firos

    i need tutorial for simple chat app like whatsApp. pls help me.

    • Yeah, It is under progress. But I have to complete some dependency articles before it publishes. That’s why postponed.

  • Mohammad

    Your website is really great!
    I do not know anything about databases in android, thanks for the link I’m about to tell me, or like the recent training on a comprehensive Explained database android do
    Translation by Google

  • Koda

    Great tutorial! but how do you take off the 22 and 50+?

    • In MainActiivty.java look for this comment // Communities, Will add a counter here

  • Ravi T.

    Please upload code which is compatible with 2.3 too. I will be thankful to you….

  • Deva

    Hi Ravi,
    Thanks for this tutorial,

    how to refresh the counter value dynamically, do i need to call the web service every time when the sliding menu is brought to front.

    • You can do that but I recommend you to use push notification. This way you don’t have to call service every time. Whenever update is there in the server, you will get notification, using this you can update counter value.

      Now how to update counter value is, update the row in the array adapter which is used for list view. And call
      notifyDataSetChanged() on the adapter. This will automatically update the listview.

      • Deva Karthik

        Thanks Ravi for your quick reply, believe GCM will the right candidate here for push notification.
        can you please share your views on jeremyfeinstein sliding menu?

        • Hi Karthik, Yeah you can GCM for this. Sorry I haven’t worked with jeremyfeinstein sliding menu.

  • Max

    Great tutorial !
    I have one question ! Why don’t you use activities instead of fragments ? I mean HomeFragment could be HomeAcitivity, etc…

    • Fragments is the best way to replace a view. You can’t replace a view if you use activity.

  • Raj

    Hi Ravi,

    Nice tutorial so thank you so much. Now I have a question that If I want to add a bottom bar as we have action bar at top in this example.I have added a bottom bar at bottom by adding a layout. but I am facing a problem i.e my bottom bar slides with fragments. I want to make it static as we have static action bar(without sliding). so please tell me how I can I achieve it. Thanks

  • Sumeet Raj

    Thanks Ravi for this nice tutorial..

  • James Graham

    Hi Ravi, awesome tutorial.

    Just one issue, I’m getting an issue with the screenshot below. Can you help?

    https://www.dropbox.com/s/fibpmp5929mh3c0/Screenshot%202013-11-19%2018.02.01.png

    Thanks

  • قلب الأمل

    Hi there,
    Thanks for the tutorial

    but I have question, how can Implement the onClick button that is in the “FindPeople.xml” for example I tried to implement it in the “FindPeople.class” but didn’t work and tried to implement it in the MainActivity and works fine.

    the big question is it efficient to implement all “onClick” events for all pages in the MainActivity?? I don’t really prefer it

    and how can I implement it in the Fragment java file for each page??
    Hope you understand my question

    thanks a lot

    • It should work. Could you post your code, how you did it

      • قلب الأمل

        I solved the problem ^_^
        Thanks a lot ^_^

        • Pranav Mahajan

          How did u solve it. I’m having the same problem. Say if I have a button in each fragment , then would I need to declare their methods in MainActivity.java , because they are not visible in Fragment classes.

          • قلب الأمل

            Hi Pranav.
            you can declare the buttons in your fragment class
            do the following:

            1. Declare the Button variable as a public variable in the class so that you can use it in any method.
            (write this code after the class name:
            Button your_button_name;)

            2. inside the “onCreateView” method write:
            a. set the layout:
            View rootView = inflater.inflate(R.layout.your_fragment_layout, container, false);

            b. initiate the button:
            your_button_name = (Button) rootView.findViewById(R.id.button_id);

            c. set the onClick listener:
            your_button_name.setOnClickListener(this);

            3. Override a method called “onClick” and let the class implements “OnClickListener”.the following code is implemented to handle a click listener event for more than one button:

            @Override
            public void onClick(View view) {
            /* This method to deal with multiple buttons
            if the class has only one button then write the
            code to handle the on click button event directly
            here*/

            switch (view.getId()) {
            case R.id.btn_search_submit: // write your button id
            Search(); /* method to handle the event when
            this button is clicked*/
            break;
            case R.id.btn_category:
            Category();
            break;
            case R.id.btn_where_to_search:
            Where_to_search();
            break;
            }
            }

            Hope you find my solution clear
            All the Best ^_^

          • Pranav Mahajan

            It worked..thanks…
            but I have another conceptual question… I was trying to do this by declaring android:onclick = “hello” in the XML file
            I had to declare the corresponding hello() function in MainActivity.java . It was’nt visible from the Fragment class. Can you explain me the difference between the 2 approaches to define button listener.

          • قلب الأمل

            Actually I tried the same way as you. then I tried to do it another way. that is how I solved the problem ^_^. I don’t know what is the difference ^_^

  • Rupesh

    Hi Ravi,
    Thanks for the tutorial
    But I have Question,how can Implement the slider menu open the current activity also moving how can implement this type of code please help me.

    • This kind of navigation is there previously. But android.com is not suggesting this way. You can see Google+, Youtube modified their application already.

      • Rupesh

        Thanks Ravi,Any code availble this type project please send the link.

  • gunawan

    Hi Ravi, Good Tutorial. I try your code, I have Question, in “home” fragment im using webview to load website, i try using refresh on Action Bar to reload webview on fragment.

    Here is my code :

    public boolean onOptionsItemSelected(MenuItem item) {
    // toggle nav drawer on selecting action bar app icon/title
    if (mDrawerToggle.onOptionsItemSelected(item)) {
    return true;
    }
    // Handle action bar actions click
    switch (item.getItemId()) {
    case R.id.action_refresh:
    // refresh

    refreshMenuItem = item;

    // load the data from server
    new SyncData().execute();
    return true;
    case R.id.action_settings:
    Intent intent = new Intent(this, Setting.class);
    this.startActivity(intent);
    break;

    default:
    return super.onOptionsItemSelected(item);
    }
    return false;
    }

    On case R.id.action_refresh: what the code to use to reload webview. Sorry im newbie and sorry for bad english.

  • SeeZa

    nICE Tutorial Ravi. do you recommend using activities instead of fragments? or does the drawer support use of activities?

  • Rishil

    Hey Ravi,

    Awesome tutorial.
    I have two questions.
    1) I don’t want to display the counter in my silder menu..I tried to remove it but it lead me to unexpected behavior.
    2) I am having two classes which extend activity. I need to open them when I click on respective list item. Is that possible ?

    Thanks in advance.

    • Yeah you can do it. When you add list item in adapter like

      navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons.getResourceId(3, -1), false, “22”)); – pass false here or don’t pass anything. It won’t display a counter.

  • Vivek Ravi

    Hi Ravi
    Thanks for your nice tutorial. But on item click is not working for me.

    • Did you called this line mDrawerList.setOnItemClickListener(….) in main activity?

      • Vivek Ravi

        Ok Ravi. I solved that issue. Thanks for your help…

  • Thinh Ng

    Hi Ravi, thanks for your example!
    I have a question, how to easy implement header section for navigation item?

  • Disk Jokey Adi

    Awesome tutorial!!
    i have a question, how to add title, image and email from url like the example image above???

  • harsh

    import android.support.v4.app.ActionBarDrawerToggle;
    import android.support.v4.widget.DrawerLayout;
    these lines r shwing error..i have also copied android support library in the libs folder of the project,,plz help!!

    • Kiitens

      having the same problem here, any tips will be great, thanks!

    • After copying it to libs folder, did you link the jar in project properties?

  • Dhanraj

    I need to create a file manager with navigation drawer, but i’m unable to inflate the list view for the file manager in the framelayout using fragment. Help appreciated

  • Pranav Mahajan

    Hi Ravi, absolutely brilliant!!
    Q- What if I have a button in each fragment. I’ll have to declare all of their listeners in MainActivity.java. That is wrong in any design . How do I resolve this issue??

    If I start a new activity(TempActivity extends MainActivity) in the “switch clause” instead of replacing the fragments,then replace the Fragment from the TempActivity, then there are performances issues. Also, the sliding animations go away. Thanks in advance..

  • Arthur

    Hey Ravi, you have some of the best tutorials on the net 🙂

    A question, there’s an issue with the native android drawer and i wonder if you have found a solution for it. If you use more than simple text and a small icon in the drawer fragments then the transactions lag a bit. E.g Try to add big images to each fragment, the drawer transactions will lag

  • Neo

    Hi Ravi,

    could you possibly add a guide regarding how to add a seperator listview like youtube apps did?

    Regards

    • Neo

      and sub description under each listview attributes? regards

  • Droid Developer

    Ravi, Please upload in app purchase demo . I am waiting for a tutorial of this from your side. Please upload it as soon as possible as it is essential feature these days.

  • Raj

    Hi Ravi,

    Thanks for quick reply and suggestion. I am not using tabs but a simple view which does not have any component on it. I have a problem related to drawer i.e when I launched main activity then it takes about 2 to 3 seconds to become visible(screen goes blank).I have placed all the code into the onResume() because I thought that due to large code in onCreate() it is taking more time than usual. but It did not solve my problem. I am in big trouble and also tried so many ways to reduce this time but could not succeeded. so please help me what am I doing wrong…

  • Kleon

    amazing tutorial!
    Can you please provide a solution with headers / sections?

  • Akshay Taru

    Does it support 2.3?

    • Rishil

      I also tried on my 2.3.4 version phone…Application is crashing.

      @ravi8x:disqus : What changes do we need to do to make it work on 2.3 ?

      I changed minsdk version to 9. Still not working.

      Thanks.

      • Akshay Taru

        Remove android:background=”@drawable/list_selector” from drawer_list_selector.xml it should work. There is bug log for this in library.

        • Rishil

          You mean drawer_list_item.xml ??

          • Akshay Taru

            yes drawer_list_item.xml sorry for typo, Remove that attribute and the app should work.

          • Rishil

            I removed android:background=”@drawable/list_selector” from drawer_list_item.xml..

            Still not working on my 2.3.4.. 🙁

          • Akshay Taru
      • Changing the minsdk to 9 won’t work. You need to include Support Library and have to do changes in code too. Like when using getActionBar(), you should call getSupportActionBar().

        • Rishil

          Please provide reference URL for the same if available.
          As I haven’t used it, I don’t know the exact steps.

          I have imported import android.support.v4.app.Fragment;

          Thanks

          • Guest

            package info.androidhive.slidingmenu;

            import info.androidhive.slidingmenu.adapter.NavDrawerListAdapter;
            import info.androidhive.slidingmenu.model.NavDrawerItem;

            import java.util.ArrayList;

            import android.content.res.Configuration;
            import android.content.res.TypedArray;
            import android.os.Bundle;
            import android.support.v4.app.ActionBarDrawerToggle;
            import android.support.v4.app.Fragment;
            import android.support.v4.app.FragmentActivity;
            import android.support.v4.widget.DrawerLayout;
            import android.util.Log;
            import android.view.Menu;
            import android.view.MenuItem;
            import android.view.View;
            import android.widget.AdapterView;
            import android.widget.ListView;

            public class MainActivity extends FragmentActivity {
            private DrawerLayout mDrawerLayout;
            private ListView mDrawerList;
            private ActionBarDrawerToggle mDrawerToggle;

            // nav drawer title
            private CharSequence mDrawerTitle;

            // used to store app title
            private CharSequence mTitle;

            // slide menu items
            private String[] navMenuTitles;
            private TypedArray navMenuIcons;

            private ArrayList navDrawerItems;
            private NavDrawerListAdapter adapter;

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

            mTitle = mDrawerTitle = getTitle();

            // load slide menu items
            navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);

            // nav drawer icons from resources
            navMenuIcons = getResources()
            .obtainTypedArray(R.array.nav_drawer_icons);

            mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
            mDrawerList = (ListView) findViewById(R.id.list_slidermenu);

            navDrawerItems = new ArrayList();

            // adding nav drawer items to array
            // Home
            navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons.getResourceId(0, -1)));
            // Find People
            navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons.getResourceId(1, -1)));
            // Photos
            navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons.getResourceId(2, -1)));
            // Communities, Will add a counter here
            navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons.getResourceId(3, -1)));
            // Pages
            navDrawerItems.add(new NavDrawerItem(navMenuTitles[4], navMenuIcons.getResourceId(4, -1)));
            // What’s hot, We will add a counter here
            navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons.getResourceId(5, -1)));

            // Recycle the typed array
            navMenuIcons.recycle();

            mDrawerList.setOnItemClickListener(new SlideMenuClickListener());

            // setting the nav drawer list adapter
            adapter = new NavDrawerListAdapter(getApplicationContext(),
            navDrawerItems);
            mDrawerList.setAdapter(adapter);

            // enabling action bar app icon and behaving it as toggle button
            getActionBar().setDisplayHomeAsUpEnabled(true);
            getActionBar().setHomeButtonEnabled(true);

            mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
            R.drawable.ic_drawer, //nav menu toggle icon
            R.string.app_name, // nav drawer open – description for accessibility
            R.string.app_name // nav drawer close – description for accessibility
            ) {
            public void onDrawerClosed(View view) {
            getActionBar().setTitle(mTitle);
            // calling onPrepareOptionsMenu() to show action bar icons
            invalidateOptionsMenu();
            }

            public void onDrawerOpened(View drawerView) {
            getActionBar().setTitle(mDrawerTitle);
            // calling onPrepareOptionsMenu() to hide action bar icons
            invalidateOptionsMenu();
            }
            };
            mDrawerLayout.setDrawerListener(mDrawerToggle);

            if (savedInstanceState == null) {
            // on first time display view for first nav item
            displayView(0);
            }
            }

            /**
            * Slide menu item click listener
            * */
            private class SlideMenuClickListener implements
            ListView.OnItemClickListener {
            @Override
            public void onItemClick(AdapterView parent, View view, int position,
            long id) {
            // display view for selected nav drawer item
            displayView(position);
            }
            }

            @Override
            public boolean onCreateOptionsMenu(Menu menu) {
            getMenuInflater().inflate(R.menu.main, menu);
            return true;
            }

            @Override
            public boolean onOptionsItemSelected(MenuItem item) {
            // toggle nav drawer on selecting action bar app icon/title
            if (mDrawerToggle.onOptionsItemSelected(item)) {
            return true;
            }
            // Handle action bar actions click
            switch (item.getItemId()) {
            case R.id.action_settings:
            return true;
            default:
            return super.onOptionsItemSelected(item);
            }
            }

            /* *
            * Called when invalidateOptionsMenu() is triggered
            */
            @Override
            public boolean onPrepareOptionsMenu(Menu menu) {
            // if nav drawer is opened, hide the action items
            boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
            menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
            return super.onPrepareOptionsMenu(menu);
            }

            /**
            * Diplaying fragment view for selected nav drawer list item
            * */
            private void displayView(int position) {
            // update the main content by replacing fragments
            Fragment fragment = null;
            switch (position) {
            case 0:
            fragment = new HomeFragment();
            break;
            case 1:
            fragment = new FindPeopleFragment();
            break;
            case 2:
            fragment = new PhotosFragment();
            break;
            case 3:
            fragment = new CommunityFragment();
            break;
            case 4:
            fragment = new PagesFragment();
            break;
            case 5:
            fragment = new WhatsHotFragment();
            break;

            default:
            break;
            }

            if (fragment != null) {
            android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
            fragmentManager.beginTransaction()
            .replace(R.id.frame_container, fragment).commit();

            // update selected item and title, then close the drawer
            mDrawerList.setItemChecked(position, true);
            mDrawerList.setSelection(position);
            setTitle(navMenuTitles[position]);
            mDrawerLayout.closeDrawer(mDrawerList);
            } else {
            // error in creating fragment
            Log.e(“MainActivity”, “Error in creating fragment”);
            }
            }

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

            /**
            * When using the ActionBarDrawerToggle, you must call it during
            * onPostCreate() and onConfigurationChanged()…
            */

            @Override
            protected void onPostCreate(Bundle savedInstanceState) {
            super.onPostCreate(savedInstanceState);
            // Sync the toggle state after onRestoreInstanceState has occurred.
            mDrawerToggle.syncState();
            }

            @Override
            public void onConfigurationChanged(Configuration newConfig) {
            super.onConfigurationChanged(newConfig);
            // Pass any configuration change to the drawer toggls
            mDrawerToggle.onConfigurationChanged(newConfig);
            }

            }

    • Sami M.

      Hi Akshay,

      As
      it is right now it supports only API level 14 (Android 4.0) and + . But you can
      “leveldown” it to Android 2.1 (API level 7) and + by making following
      modifications:

      1) Install
      and add Support Librairies v4 and v7 to
      your project ( http://developer.android.com/tools/support-library/setup.html )
      2) Delete
      android:minHeight=”?android:attr/listPreferredItemHeightSmall” and android:textAppearance=”?android:attr/textAppearanceListItemSmall”
      lines from “drawer_list_item.xml”, you can style it in another way or
      just keep it without theses lines.
      3) You should extend ActionBarActivity instead of
      FragmentActivity or Fragment
      4) Change your App Theme
      to @style/Theme.AppCompat or @style/Theme.AppCompat.Light etc…
      5) Change calls to
      getActionBar() for getSupportActionBar()
      6) Change
      calls to invalidateOptionsMenu() for supportInvalidateOptionsMenu()

      Regards.

      • Latino_Review

        Finally i made it works, thanks to your tips. But there’s something wrong in left list the selected item doesn’t change the color to red like in the image in tutorial. But it happens only on device a Xperia X10 2.3.3, but in the AVD with Android 4.2 it runs fine. Any idea on why it happens ?

  • Rhino

    Hi Ravi, thanks for the tutorials.
    I have a question, how to do it if I would like to work it with WebView?
    Thanks

  • Joseph

    Nice!!! I just wanted to know how to put webview and sharedpreference inside

  • Ruchi Sharma

    Please upload demo of in app billing. I always wait for tutorial from you. They are extremely helpful. Please provide demo of in app purchase or a well defined tutorial link, i will appreciate this. Thanks in advance

    • Thanks Sharma for the suggestion. I also never tried it before, let me try once.

      • Ruchi Sharma

        Thanks for your reply.. I have search on many websites and blog but didn’t find any step by step implementation and i am lil confused too with the procedure. i am hoping you will upload it soon.. 🙂 🙂

  • Eric

    Hi Quick question: Why did your MainActivity extend Activity and not FragmentActivity?

  • Abdullah

    Hi Ravi, can we use expandable list for this slider?

  • Rishil

    Hey Ravi, How do I integrate

    Android Tab Layout with Swipeable Views.
    I want to display a tab layout when i click on a link from Sliding menu.

    Thanks.

    • Hey Rishil,

      Using both navigation drawer and tabs are not suggested way.

  • chavika

    Hi,
    I was tryin to change the color of the actionbar.it seems its been override somehow.can you pleas let me know how to change the action bar to dark

  • chavika

    Hi,
    I was tryin to change the color of the actionbar.it seems its been override somehow.can you pleas let me know how to chage the action bar to dark

  • Chavika Manage

    Hey Ravi,

    I was trying to change the action bar style to DarkActionBar but it seems its been overridden somehow.Can you please let me know how i can overcome this

  • Manoj Kumar

    Hi Ravi,

    Is is possible to add icon in option menu item which overflow from action bar?

    • We can’t show icon to overflow menu item.

      • Manoj Kumar

        Thanks Ravi for confirmation.

  • Chavika Manage

    Hey Ravi,

    Is it possible to use scrolling tabs with this example?

  • jabbar_jigariyo

    Hey Ravi,
    I have a question regarding navigation drawer pattern.
    Should I use all fragments or all activities ? I can’t decide that and I don’t understand significant importance of one or another.
    Please share some knowledge in that area. Thanks.

  • sindhu

    Hi Ravi,

    I have a question about the fragments. You called each fragment using this statement
    fragment = new HomeFragment();
    but i have a fragment activity instead of a fragment like this
    public class HomeFragment extends FragmentActivity implements

    can you tell how to call this class from the main activity.

    Thanks

    • Hassan Samii

      i have the same problem!! have you solved it?

      • sindhu

        Not yet..waiting for somebody’s reply..

    • You cannot call FragmentActivity like this.
      FragmentActivity extends Activity and instance of Activity cannot be created using a Constructor. However, Fragment is direct child of Object, and is allowed to create instance unlike Activity and its descendants.

      If you really like to use your FragmentActivity here then try to convert that class to use Fragment only.

      Hope it helps..
      http://www.pcsalt.com

  • sachidananada naik

    Hi Ravi,

    This tutorial is really nice, i would like to add nested sliding menu’s… how can i do it ?? please let me know

  • willian

    Ravi

    very good your tutorial is what I needed, but I need to make some adjustments on it.

    1 – I need the menu instead of opening from left to right, it opens from right to left. is this possible?

    2 – the list I need to mark several items and make the filter for branded items, this case has to be more than 1 item, ie, 2, 3, 4, … items. I can also do this in your example? thank you

  • Aditya Kashyab

    I m Coding it on Android 2.x

    i get every thing fine else 2 things messed up in my app

    1) i could not use fragment class from

    /**
    * Diplaying fragment view for selected nav drawer list item
    * */

    ……………………………

    i just kept whole case , if and else commands in /** **/ (comment box ) and then app work fine 🙂
    can any1 help me to fix it 🙂

    And
    2) My Navigation Drawer is not much fancy as shown in Vide0
    how to make it fancy… no pictures are displayed in my Navigation Drawer…..
    can any one inform me how can I edit it and make it looks like really cool 🙂

    • Ngô Văn Bằng

      you can using android support v4 and android suport v7 for android 2.x

  • Simon Willcock

    Thanks for this tutorial. It was very useful and I’m sure I’ll refer back to it multiple times. Keep up the great work.

  • thomas

    When I try to implement home fragment as listfragment it was unfortunately stopped.. How I fix this problem?

    • Check the eclipse LogCat for error report.

  • Nguyễn Ngọc

    Hey Ravi.

    I had a button in HomeFragment. How to Click this button to move to WhatshotFragment?

    • Ngô Văn Bằng

      you can replace this fragment by other using fragmnet mannager

      • Nguyễn Ngọc

        Change the color listview?

        • Ngô Văn Bằng

          no “replace” using framelayout

  • xerox

    Hello Ravi,

    Thank you for your great example. I adapted to use it on sdk 11, but seems to be a problem. When i open the drawer, onPrepareOptionsMenu doesn’t get the call. On sdk19 the same code works great.

    https://github.com/sgolivernet/curso-android-src/tree/develop/android-navigationdrawer this project has the same problem than mine, can you see the error?

    Thank you very much.

  • Raaz K Razi

    how to add header for the list view?

    • Neo

      really hope he will update this guide as well, because it is really important for me 🙁

      • Ngô Văn Bằng

        so sory .i have send exampe for you.check email.

        • uno_xx

          I want this too, can u send me to vishalmeham2@gmail.com
          Thanks !

        • Neo

          Hey Ngo, I have added you in facebook, could you accept it please?

    • Ngô Văn Bằng

      public void addHeaderView ( View v) this is method of listview object

      and View here you can inflate from xml file.

  • Bilal

    Hi,

    Great tutorial and thanks for taking the time to show us how to use this awesome feature. I was wondering if you can provide me with a little assistance. I wanted to know how to get the counter to load asynchronously? For example every time I click a button and a fragment activity start i add this activity to a table. This will create a history of every called fragment. I have on the navigation drawer a tab called History with the number of entries from sql db. I wrote a method to read the DB and get the value but it will only show the updated value after close the application and restart it. How do I get the value to load asynchronously in the background? Any ideas would be appreciative.

    • May you are calling your code in onCreate method. This is why it is not getting called evertime. Try to move to code to onResume. Please let me know if you did it already.

      • Bilal

        Thanks for taking the time to assist. I will try that today after work and let you know how it goes.

        Kind Regards,
        Bilal

        • Bilal

          Hey, I couldn’t get it to work. I gave up on the counter. Just going to leave it as is and then the click on the tab they can see the count at the top of the fragment.

  • rach

    Hi Ravi,
    Great tuto thank you :).
    Can you please post the same tuto with support library to work under 2.x or higher … Thanks

  • youssef

    Great tutorial and thank you
    Plz code source

  • zaid

    how change location menu form left corner screen to right

  • zaid

    how remove icon g+

  • Loui

    Great tutorial for navigation drawer. I’ve had a look at quite a few
    tutorials regarding navigation drawer. How do you set an image at the top of navigation drawer menu with selectable list items below like the middle image you have at the top of your tutorial?

    Any guidance will be much appreciated!

  • Ruchina

    Great tutorial it works really good. But after using this my send email or buttons aren’t working in the fragments. can you help me with it. It doesn’t have any errors and it should work fine. Also the internet function is also not working. Do I need another code for it?

    • Ruchina

      I manage to get the click events. But after it does the work the navigation drawer disappears. How do I keep that always when on click events and all other events.

    • Loui

      Where you say the internet function doesn’t work, you may have to add the permissions in android manifest:

      • Ruchina

        I have add that too. Then when I called the function and somehow it worked and after that the fragments the navigation drawer disappears. and the email client won’t work too. When I did it without navigation drawer it worked. I’m new to the navigation drawer can you help me in it?

  • Ricky

    thanks for great tutorial Ravi. i want ask,is it possible that HomeFragment change to activity?
    Or any suggest about that?thanks before.

  • Richard

    This tutorial was really great and informative. i was wondering in case that I want to put a listview on the HomeFragment, and load items on it by JSON parsing, how would I do that? I tried integrating your Multi Level ListView with this one but it wont allow me since this is using Fragments instead of Activity. Is it impossible or I’m just making mistakes on my end? Thanks a lot Ravi.

    • Ricky

      i have been try parsing with JSON and succeeded. put your before return rootview.

      like this :

      @Override

      public View onCreateView(LayoutInflater inflater, ViewGroup container,

      Bundle savedInstanceState) {

      View rootView = inflater.inflate(R.layout.edit, container, false);

      User = getActivity().getIntent().getStringExtra(TAG_User);

      id = (TextView) rootView.findViewById(R.id.txtLabel);

      new LoadUser().execute();

      return rootView;

      }

      private class LoadUser extends AsyncTask

      then code like usual. it works for me..

      • Richard

        Thanks for the hint Ricky,, gonna try this now,

      • Richard

        Ricky still wasnt able to code it coorectly, i’m still new to this android development and I’m trying to use the JSON parser in this tutorial http://www.androidhive.info/2012/10/android-multilevel-listview-tutorial/ ofcourse with the AsyncTask to load the list. but still no good.

      • Richard

        Can you give me an example on how you do it??

      • Petr

        Hi, this is really nice code, all works fine, but when running this new LoadUser().execute() as AsyncTask,I got a problem showing ProgressDialog. Actually I don’t know how to get proper Context as ProgressDialog paramter. Can you advice ?

        • Petr

          I just found the solutio, there must be Context parameter in the AsyncTask that is passing the Context to AsyncTask constructor. Now it is perfect. Thank you all guys. I recomend to watch hundereds of tutorials and codes to digg in. Try try try … good luck.

  • Abd

    Thanks a lot for the tutorial. One question, if I have a complex home page, should I put all the methods and functionality of Home page inside HomeFragment.java? Or should I create one activity for that (let say HomeActivity.java) and start that activity from HomeFragment.java using startActivity?

  • supreeth

    Hi Ravi followed your code and got the result, but the problem is i am having a list of items in drawer about 10+ but with this example when i implemented i could see the items only which comes in screen, rest nor i am ale to scroll down or do anything, Best reference is i want some thing like a facebook kind implementation. Can you please guide in that issue………

    • uno_xx

      I have a scrollbar even if i put more than 10 items. Please check your code again!!

  • Can Yastıoğlu

    Hi, this is imagine tutorial. Thank you very much.

  • Jorell Rutledge

    How would I add a webview to each menu item?

  • Wilian diogo pasternak

    Friends are the CONGRATULATIONS for the design and quality that is PERFECT. I want to know if I can use some software on my menu? What kind of license?

    Hug.

  • Virender Dall

    not working on api 11, throwing error of
    getActionBar().setHomeButtonEnabled(true);
    how can i fix this?

    • KR2435

      You just need to change the minsdk version from api 11 to api 14 into AndroidManifest.xml file

  • sureshbabu

    can someone tell me emulator configuration for running this navigation drawer…

  • FG

    There is error in your project code!!!!!!

  • Giancarlo

    Great Tutorial!!
    I have a question: how can i put a “Title Header” in nav drawer like the youtube image on top of the article?

  • Amit Bhaliya

    When i add below code in class FindPeopleFragment
    TextView textView = (TextView) findViewById(R.id.txtct);
    it will generate this error like “The method findViewById(int) is undefined for the type FindPeopleFragment” so how can i solve this please send me replay.on this id amit.potent@gmail.com
    pleaseeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee
    replayyyyyyyyyyyyyyyyy

    • Hiếu Giề

      i have same question as u )):
      how can i resolve this problem ?
      thank

    • asmaa

      FindPeopleFragement is a fragment , you sould work with Activity

      • Amit Bhaliya

        i will be find then what i should be change there plz reply meee.

        • Akatsuki777

          Create a view variable and use it to reference the call….
          View v;
          TextView textview = (TextView) v.findViewById();

  • Laurentiu

    It crashes on Android 2.3.3 (API 10) even the support library v4 is used…

    • Hultan

      it has a minimum of API 14

      • Laurentiu

        Meaning?

        In AndroidManifest file we have the following:

        From where did you get the API 14?

        PS: In order to run it on API10 I did change the mininum sdk version to 8-10 (based of the fact that v4 support lib is used) and taget version to 19 (there are some bug fixes) but it did not worked… It’s important for me to have a working project for as minimum as API 8.

        • Changing only the SDK version in manifest won’t be sufficient. You need to replace some code too when you included v4 support library.

          • Laurentiu

            The support library is already included in this project… Check the zip file.
            That’s why I thought it will support older Android versions. I guess I have to look for other similar projects as this isn’t good for me.
            Thanks for your time.

          • Dimpho

            Yah the support library is already included in the project but due to minimum SDK issues, the classes used were in the base library SDK because they were available for those SDKs but if you want to target minimun SDKs like 2.3, 2.2, 2.0, you have to change where you import some of the classes e.g FragmentManager, FragmentTransaction classes are not available in lower APIs but we need them to get this project working, so you have to hunt them in android.support.v4.app. Also if there are some classes needed but you dont find them in the base libraries and v4 support, you can also look for v7 support, reference it to your project and fight to get it working, in future.

          • Laurentiu

            Juan Rivero already made this work. He used the Ravi Tamada source code and updated to work with lower Android versions. Here is the library: https://github.com/rimeju/SlidingMenu

          • Latino_Review

            It dind’t work to me ! I keep getting android.view.inflateException !!

        • Juan Rivero

          Check my repository: https://github.com/rimeju/SlidingMenu

          Compatible with api 8. 😉

  • Ivan

    Great tutorial again!! Thanks Ravi

  • Back Packer

    Thank you very much man ! it’s a very good tutorial !

  • Devjoks

    Hi. Sorry you know how I can put a FragmentActivity in replace to Fragment for add GoogleMap ?

  • dee lee

    hi thanks for the tutorial! how would i simply use list item to activate something other than fragment? like if i want to do settings screen(preferenceActivity/fragment

  • James Graham

    Have you had the opportunity to try it with the new KitKat translucency effect? I gave it a go and what I am finding is that the fragments end up going behind the action bar and the list view of the slide in menu goes behind the action bar too!

  • Sweetie

    Hello, this tutorial is great but when i click the list, it does not go to the page i want to display. It only display the 0 when if (savedInstanceState == null) {
    // on first time display view for first nav item
    displayView(0);
    } how can the list be clickable?

    • uno_xx

      It is already clickable

  • Banucho Cassamo

    Hi!

    Is it possible to implement swipeable views on one of the fragments implemented here?

    for example on HomeFragment implement an tab layout with swipeable like this turorial:

    http://www.androidhive.info/2013/10/android-tab-layout-with-swipeable-views-1/

    but not loosing the navigation drawer?

    • Banucho Cassamo

      I want to do something like google play. we have navigation drawer and swipe views with tabs. How to do both things on same app?

  • Amarjeet Singh

    Hello Ravi..
    I am really fan of your coding standards and examples.. I am facing few problems in this example. Can you please clear.. few things.. So i can use this example in my project..
    1. Is it compatible with sdk version 11. (Or Required api level 14).
    2. When i am running this on android 3.0 then getting error.
    {java.lang.UnsupportedOperationException: Can’t convert to dimension: type=0x2}
    3. I have also tried to use support library but its giving error. Where i have to change the code?
    Please reply for my questions..
    Regards
    Amarjeet Singh

  • dr tarik

    thank you so much for all the efforts you make to develop the tutorials, I’m really impressed
    if i can ask you about how can we use that with master-detail fragments?

  • tesla

    Thank you so much for the tutorial !!!

  • galiley

    Thank you so much . this article helped me .

  • uno_xx

    Great article. It helped me a lot. But the text like”50+” becomes invisible sometimes even if the code is correct.

  • Bhupendra Singh

    Nice article, I have a query, how can we implement this in devices with lower API level, say for example API level 11, is there any way???

  • guest

    You should also include to link for sample project download…

    • Ravi Tamada

      It is there at the starting of the article with DOWNLOAD CODE name.

      • guest

        that link is not working for me. do I need to subscribe? but even if I try I don’t get a confirmation mail or anything. I’m stuck on an empty page called http://download.androidhive.info/firewall/firewall.php I tried with different browsers and on different computers

  • Pranav Mahajan

    Hi Ravi,

    I want 2 navigation drawers on the same page.. on the left as well as right…. how do I do that??

  • Juan Rivero

    Thank you very much for the article, it was quite helpful. at first, the example you leave us is compatible only with version 11 of the api. I managed to make it work with version 8 api. Here is the link and I hope will be useful.

    Android Studio 0.4.2, API level 8.

    https://github.com/rimeju/SlidingMenu

    Greetings.

    • Unnati

      Hi,
      Can you share the link please? it will be really helpful..

    • Pooja

      You provided link is dead. Can you please update it.

    • Nikita

      Greetings! Prompt how to use these files?

    • Никита Гордеев

      Please help me collect this application for api 8. Did not get to do, help 🙂

  • Tejaswi

    Hey I really liked this article but then what id I want to add activity/FragmentActivity instead of Fragment?

    • Tssomas

      define the view then do view.findViewById();

  • Sohail Zahid

    plz if you can download the Source code pLZ PLZ send it to me on
    bsits11a11@gmail.com
    i will be very thankful to you

  • Eric

    How can you add a title to the drawer items similar to the youtube and facebook examples that you provided? I am trying to add a title that separates the contents of NavDrawerItem, but can’t find an easy solution. I would like a smaller font, so that it is obviously a title.
    Thanks,
    Eric

  • ahmed ashour

    Hi Ravi,
    I try to Download Source code but every time, I turn to this Link
    “http://download.androidhive.info/”
    and nothing happen.

  • وليد ساسي

    please can you give us the code because we can’t download it

  • Karan

    Hi Ravi.

    OnClickListener event is not working.

    Here is my the code.

    package com.karan.test;

    import android.annotation.SuppressLint;
    import android.app.Fragment;
    import android.content.Context;
    import android.content.Intent;
    import android.os.Bundle;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.Button;
    import android.view.View.OnClickListener;
    import android.view.ContextThemeWrapper;

    @SuppressLint(“NewApi”) public class Photos extends Fragment implements OnClickListener{

    Button NewPhotos;

    public About(){}

    public void OnCreate(Bundle SavedInstanceState) {

    super.onCreate(SavedInstanceState);

    }

    @Override

    public View onCreateView(LayoutInflater inflater, ViewGroup container,

    Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.fragment_about_me, container, false);

    NewPhotos= (Button) rootView.findViewById(R.id.btnNewPhotos);

    NewPhotos.setOnClickListener(this);

    return rootView;
    }

    protected Context getApplicationContext() {

    // TODO Auto-generated method stub

    return null;

    }

    @Override

    public void onClick(View v) {

    // TODO Auto-generated method stub

    Intent i = new Intent(getApplicationContext(), NewPhotos.class);

    startActivity(i);

    }

    }

    Can u please tell me what went wrong.

    Thank

  • Rodelio Imutan

    i want to use an image from the web as an icon, how do i do that?

  • Filip Luch

    could you please extend this article and make right and left menu drawer? (in the right part usually notification or some other list)

  • Oscar

    Inside of the optioms from menu I need to show a listFragment , example (In case 3) .. can you help me?

  • feresr

    Wow! that amount of code just to create a simple slider :/

  • Akshay Taru

    Hi Ravi, If you have time then please consider to Update this tutorial to ActionBarCompat

  • Nikita

    Greetings! Tell me what to do, so the application was working for API 8? I have already downloaded the files that the author gave at this link https://github.com/rimeju/SlidingMenu . What do I do with these files?

  • Wes

    This tutorial really helped me A LOT. It is very clear and also the code is well commented. Thank you very much!

  • Guest

    how to add Searchview at the top?

    • Shukerullah

      You can use searchview in actionbar

  • OnderiX

    Hi I used ExpandableListView instead of ListView. I fill ExpandableList with adapter. Then I click List group item to
    expand to see the children items. But when I click group item menu
    ExpandableList doesnt expand but slider closes instead.

  • Shukerullah

    This is awesome tutorial !!

  • Gilbert Sarip

    Is it possible to hide the title bar?

  • Mike

    How do you add a Swipe tab inside each fragment, such as a tab in PhotosFragment when its clicked and another set of tabs in CommunityFragment when thats clicked?

  • rehnen

    It’s amazing to me that google makes this awesome new feature, and yet makes it so har to implement it. Make your own adapter or get fucked!

  • Edwin

    Hi, congratulations and thank you very much for sharing your knowledge …

    I have a problem and hope you will please help me fix it.

    I’m trying to embed said in this tutorial:
    http://androidsensei.net/reproduciendo-videos-de-youtube-en-tu-aplicacion-android/

    one of the menu itmes your tutorial, but I can not do it. I know it’s easy for you because I honestly am starting with this.

    (Google traductor Sorry)

    Thank you very much.

  • Yasmine

    Hi, great work you did here, I downloaded the source code and modified it to work with api level 8 and above. I’ll post the source on github and reference you if it’s okay with you. Thanks for sharing.

  • Marcin

    Thanks a lot. You saved my life: P

  • Yasmine

    Here’s the code that works for earlier versions of android (starting from Api level 7 ) https://github.com/GreenApplee/SlidingMenu-Android
    hope that will help.

  • Bhavesh Shah

    How to save states of edit text in above sliding menu example. i had put one edit text to people fragment but when i revisit it it is blank.

  • Boris

    I have problem with the performance of this implementation.
    When a heavy layout is loaded in the fragment, the sliding menu animation lags a lot.
    This happened when I put an HD photo as background of the fragment.

    Any ideas how the sliding animation can be optimized?

  • Juan Rivero

    Here my code based from this project, i use Android Studio 0.4.4.
    Compatible Api Level 8.

    https://dl.dropboxusercontent.com/u/16565596/SlidingMenu.zip
    or check my repository: https://github.com/rimeju/SlidingMenu

    🙂

  • dr

    hi have to some problem in right side slider menu to use pls help…….
    how to change slider in right to left move….

  • Guest

    Can we change the Actionbar(g+ icon) when we click the item list?

  • pk

    I’m new to the usage of Fragments in android. Basically I’ve created a slide menu using Navigation Drawer. So as I understand it all the menu pages are Fragment. If I click on home I go to the HomeFragment extending Fragment class that has attached its fragment layout. Now I want to implement a tab layout for the home page. but to use tab layout i need to work with Fragments that extend FragmentActivity. How do I combine know these 2 things because they are not compatible!

    • As android suggested, we should not use navigation drawer and tab navigation together.

      • Mike

        Ok, but forget about what Android suggested. They are implementing tabs and nav drawer on google play, google music and other apps. Can you answer his question though, if possible? Thanks

        • Hamboy75

          haha exactly, dont forget about adsense and analytics apps

          • Jasson

            any help i am in the same question……

  • Bob

    Please .. i want to make sliding View … as it at the start of any application to tell user about
    ” what application do ” and then register or log in .
    — Thank you .

  • Android_Rocks

    this Link not working for Api level 8. please provide valid source code
    i have download your source code from https://github.com/rimeju/SlidingMenu but when i import project on eclipse is cant import. give a valid source code please

    • Juan Rivero

      This project is for Android Studio not Eclipse. 🙂

  • Jej

    Great tutorial, thank you very much for your work !

  • Latino_Review

    Great tutorial, it runs fine on my AVD with Android 4.2.2 but it crashs when i try to run it in my divice a Xperia X10 Android 2.3.3. I got this error: android.view.InflateException: Binary XML file line #18: Error inflating class

  • Rafiq

    Great! it works for me at first. But problem happens when i start using media player in Homefragment. The audio will stop when i swipe to another fragment. i want audio to play at background when i swipe to another fragment.

    Secon problem is, if i dont do anything on HomeFragment and just swipe to another fragment, apps will crash.
    Please advice. Thanks.

    • Rafiq

      Pls ignore this problem since im solved it already.
      Now, what i found is, when im playing audio stream in HomeFragment menu, and i move to any menu, the audio will still playing at background.
      But, if im comeback to HomeFragment menu to stop the audio, the stop button will not function anymore. I had to force close it.
      Please advice, thanks

  • Zubieta

    What if I don’t want the Fragments to be created over and over again when changing between them? Lets say, in a fragment I got a game, and in another some settings.. thanks!

    • elimence

      I’ve been thinking of same, the best solution i can think of now is simply to declare global variables for each fragment, initial them in onCreate, and then in the displayView method, assign fragment to the appropriate reference.

  • anthony

    thank so muck nice demo

  • aakash narla

    Thank you so much for excellent demo it help a lot for my project. Actually i have another question to be asked “How can we add youtubePlayer with extends fragment ?” Plz help me regarding this.

  • Bhavika Joshi

    Thank you very much.. It is very useful… But how to connect this project(Sliding Menu) with my project??? Can you explain it with example???

    • elimence

      this is not meant to be a library project, just copy the pertinent codes into your project and modify as necessary, that’s it

      • Capkin

        do you also know how can I download Images to every Fragment? if you know please help
        thanks….

  • Thank you. This is great. How can we add group menu header? Please help.

  • RKK

    Hi,

    can you give one example on ExpandableList incited of Listeview , position 2 and 4 is Expandable.

    using Slide menu

  • Kaustav Ghosh

    Now there is one problem.I want to launch an activity from a fragment.Suppose on clicking the home fragment my java page hove.java which extends Activity will launch.How to do that???Please Help.

  • Yurisehochi

    Hi All i need your help guys i have a problem and its pissing me off , the inflate layout on this java files doesnt work

    NavDrawerListAdapter.java

    mInflater.inflate(R.layout.drawer_list_item, null);

    And this HomeFragment.java

    inflater.inflate(R.layout.fragment_home, container, false);

    like he cant find the drawer_list_item.xml file and fragment_home.xml files

    • Lior Gavra

      You have to import the class R class

      • Hunter

        I’m getting this same error. How exactly do I import this class?

        Thanks in advance.

  • Lakshmi

    Thank you! Great demo.

  • Gilang Pradana

    Hi Ravi, thank you for your tutorial…
    but i have an error in “fragment = new HomeFragment();”
    it says “type mismatch : cannot convert from HomeFragment to fragment”
    can anyone help me???
    FYI i’m using eclipse, not AndroidStudio..

  • Ronen Hayun

    how can i just push the view (home, people) when the sliding menu is appear? not just make the menu on top of it..? (Like in youtube)

    thanks..

  • Carlos Morais

    How do i set a drawer (menu) header?

  • Zee

    Where do I download all these drawable resources?

  • Downloaded code have an error. Change:
    import slidingmenu.model.NavDrawerItem;
    to
    import info.androidhive.slidingmenu.model.NavDrawerItem;

  • Cesar

    GUYS PLEASE HELP !!!! , how can i set my own titles ??? im not able to do it

  • Rafiq

    Its working great but using media player in menu A and swipe to menu B then back to menu A will make the media player in menu A to unuseable. Means, i cannot press stop….play….pause…

    • Andrea Rinaldi

      I think the problem is in your code, maybe you should check how you manage the media player when switching to menu B and then back to menu A 🙂

      I suggest you to read MediaPlayer documentation, I’ve found it very useful and well-done! Good luck 🙂

  • mahul

    nice thanks for solve the code problem

  • Andrea Rinaldi

    Thanks man!

  • Ali el zein

    Im new to android please can you tell me how to add refresh to actionbar

  • hackii

    thank u travis really its a good tutrial

    can u tell me, how can i edit or change content of every fragment??

  • tiepnv

    why when i add about 16 NavDrawerItems:
    navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons
    .getResourceId(5, -1), true, “50+”));

    => some items don’t show count?

    • John Locke

      Because you are adding items manually. Notice that you are calling navDrawerItems.add 5 times…. I would suggest you to do a for loop to add all your times, I did something like this :

      for(int i = 0; i < navMenuTitles.length ; i++){

      navDrawerItems.add(new NavDrawerItem(navMenuTitles[i], navMenuIcons.getResourceId(i, -1)));

      }

      Then you need to update the displayView method accordinly.

  • Abbas

    Thank you so much. Very nice and awesome explanation. Keep it up, please.

  • Boltt

    thank you for your tutorial. what if entered listview / scroolview in fragment_home.xml,, etc.. scroll function on listview / scroolview not functioning.

  • Maloclm

    Has anyone figured out how to add headers to the navigation drawer?

  • Lê Trường Sơn

    Please help me!

    How to add a HEARDER LIST to the Sliding menu?

  • Georgi

    To add a HEADER LIST:

    ViewGroup mTop = (ViewGroup)inflater.inflate(R.layout.listview_header, mDrawerListView, false);

    mDrawerListView.addHeaderView(mTop);

    • John Locke

      How do you do it exactly if you want to have a header in the middle of the list? Should I then split the list into two and add the header to the second one? thanks

  • Nhexia

    How can add activity on every fragment? thanks 😀
    examplex

    i add button on home? and i want to toast onclick of the button? where can i put it? or where i will create a fragmentactivity? thanks

  • Wolfs Pelz

    First, i wanted to say “thank you” for your great tutorial. I’ve searched very long until i found this tutorial, the only one that works for me. Now, I wanted to integrate my app into that, which I made with your tut, but I can’t use e.g. intent in the fragments. I tried using FragmentActivitys too, but it didn’t work. Can you help me?

  • acushlakoncept

    Thank you very much, you tutorial was very useful. I am currently using it to develop an app for my church hymn book. How can I add a search box to the mDrawerList.

  • Wa Wa Tor

    Hello everyone, Thanks for this tutorial.

    I would like to add in one of the fragements a calculator page but I don’t kown how to add my code in the java class. Where to I start in here ?

    public class FindPeopleFragment extends Fragment {

    public FindPeopleFragment(){}

    @Override

    public View onCreateView(LayoutInflater inflater, ViewGroup container,

    Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.fragment_find_people, container, false);

    return rootView;

    }

    }

    And I need to add “implements OnClickListener” do I put it at the top.

    Sorry about a probably very basic question but I am new to android app making.
    Thanks for your help.

  • Guest

    I need put one ListView in fragment, but this array doesn’t work

    // Find the ListView resource.
    mainListView = (ListView) rootView.findViewById( R.id.mainListView );

    // Create and populate a List of planet names.
    String[] planets = new String[] { “Mercury”, “Venus”, “Earth”, “Mars”,
    “Jupiter”, “Saturn”, “Uranus”, “Neptune”};
    ArrayList planetList = new ArrayList();
    planetList.addAll( Arrays.asList(planets) );

    // Create ArrayAdapter using the planet list.

    —–>>>>>> THIS DON’T WORK
    listAdapter = new ArrayAdapter(this, R.layout.simplerow, planetList);
    —–>>>>>> THIS DON’T WORK

    listAdapter.add( “Ceres” );
    listAdapter.add( “Pluto” );
    listAdapter.add( “Haumea” );
    listAdapter.add( “Makemake” );
    listAdapter.add( “Eris” );

    // Set the ArrayAdapter as the ListView’s adapter.
    mainListView.setAdapter( listAdapter );

  • Diego Sanches

    I need put one ListView in fragment, but this array doesn’t work

    // Find the ListView resource.
    mainListView = (ListView) rootView.findViewById( R.id.mainListView );

    // Create and populate a List of planet names.
    String[] planets = new String[] { “Mercury”, “Venus”, “Earth”, “Mars”,
    “Jupiter”, “Saturn”, “Uranus”, “Neptune”};
    ArrayList planetList = new ArrayList();
    planetList.addAll( Arrays.asList(planets) );

    // Create ArrayAdapter using the planet list.

    —–>>>>>> THIS DOESN’T WORK
    listAdapter = new ArrayAdapter(this, R.layout.simplerow, planetList);
    —–>>>>>> THIS DOESN’T WORK

    listAdapter.add( “Ceres” );
    listAdapter.add( “Pluto” );
    listAdapter.add( “Haumea” );
    listAdapter.add( “Makemake” );
    listAdapter.add( “Eris” );

    // Set the ArrayAdapter as the ListView’s adapter.
    mainListView.setAdapter( listAdapter );

  • Bharat Jiyani

    Awesome 🙂

  • Kuroro Lucifers

    How to add multiple header to the Sliding menu?

  • shree

    hi..
    i had created package named shree.model undera src folder.. but when i extend shree.R from another package it shows off me error. Please help 🙂

  • Anthony Young

    Hi ! Thanks for your awesome tutorial 🙂

    I need to show FragmentActivity instead Fragment when I select an item menu. And from my new FragmentActivity I need to have my navigation drawer too (the same navigation drawer like my MainActivity).

    How can I do that please?

    Ps: I want the same behavior like Play Store app about menu using.

  • ACHIN VERMA

    hi, when i run this demo it first shows the Home Fragment and i have login screen in Home Fragment, and i at that time i don ‘t want to show the navigation drawer , means when i am on the home screen , and if user clicks the button to open the drawer at that time i don’t want to open the navigation drawer drawer, please guide me where should i change in the demo?

  • Carlos Linares

    so complicated

  • harsh

    thnkz itz very helpfull code nd i want the set profile on this drawer layout like google+ app in above 3 figure can u send me some code ??

  • Amit Vyas

    Hi, This is a very nice , well written , article. Thanks.
    I was trying to figure out how to slide action bar when navigation drawer is displayed. SlidingMenu library from Feinstein does that quite easily. Also would you like to comment on Which is your recommended way navigation drawer or slideingmenu?

  • skander

    what should i do to make it run on API 8 ?

    • im

      assuming your using sherlock action bar. work all, but the listview selected menu color red dont works, because state:activated of selectionlist has introduce in api 11, im finding a mode for this work. ty

  • skander

    what should i do to make it run on api 8 ?????

  • dhnjy 18

    Hi, I found this tutorial very helpful. Thank you so much.

  • bhavana bhat

    Hello, everyone

    The sliding menu is just awesome, am building an app and i need to add google map v2 as a fragment for one of the menu i tried doing it but the app is force closing. I have a last date to submit my app can anybody help me out by integrating google map v2 in the above code or mail me at t.bhavanabhat@gmail.com. ill be really greatfull.

  • Michael Mugo

    Hi.
    I found this tutorial great! Many thx for it. @Ravi Tamada. Do you mind if I used the source code and reference it for a side project I am carrying out?

  • Chí Trịnh Minh

    Hi, tks for your great tutorial!

    May I have a question? Could we manually set the red area which show the selected item in drawer? Because I want to make an Exit button at the end of the list. When clicking on the Exit, there will be a dialog with Cancel and Ok button. But if I click on the Cancel, the red rectangle is on the Exit button but not the item clicked before, that doesn’t logical.

    Thank you!

  • Pushpendra Chouhan

    Very neat and clear explanation. I have just successfully created my own navigation-drawer with the help of your code. You made my day.. cheers!!

    Thanks..! 🙂

    • Stefan

      Hi Pushoendra, I have a RSS code that I would like to integrate into the app but am unsure how to go about this. How do I make the activity start when somebody clicks on the home tab under the Navigation Drawer? You help is very much appreciated.

  • Nik

    Hi,
    Very nice tutorial, thanks.
    How can I save the state of each fragment when switching between them. For example after editing an EditText puted at the Home section, choosing another section from the SlideMenu and than switching back to Home the EditText is reseted. Any idea of how to organize the save-state ?

    • Nik

      I’ve already solved the problem, using the methods: ‘fm.(…).addToBackStack(“hi”).commit();’ and ‘fm.popBackStackImmediate();’ and FragmentManager fm = getFragmentManager();

  • dhnjy 18

    How can I use this navigation drawer for multiple activities?

    • Duy Nguyễn

      I think also like you, it just work with fragment

    • Duy Nguyễn

      I know how to do it, you can use function getActivity() before some function such as
      Intent i=new Intent(getActivity(), Login.class);

  • Jeeten Parmar

    I want to add Tablayout with this Slider. How to do this ? I have used this same slider and It will be better if I don’t need to change more code.

  • hamed

    hi , thanx for this tutorial
    how can i open this slide bar by clicking on a button in one fragments ?

  • Android User

    Hi thank you for the great tutorial! Can you please tell me how I can change the gravity of the ActionBarDrawerToggle to the rigth? I want the ic_drawer icon to appear on the right of the Action Bar. Thank you

  • Nexus 5

    Excellent tutorial! I was looking for that for days now. Thank you!!

  • Hernan Dario Cardenas

    Excelente trabajo me ayudaste con mi proyecto

  • dammak

    why it doesn’t work with android 3.0!

    • Anggrayudi H

      only work on API 11+. If u want to create them on API 8, 9, or 10, u can add “appcompat-v7 library”.

  • Firoz

    How to change upper header background color??????

    • PESfcs .

      Look at the MainActivity class – at around line 96.

      try and add the next line –

      getActionBar().setBackgroundDrawable(getResources().getDrawable(R.drawable.add_state));

      now u can change the – R.drawable.add_state

      into an selector xam file that you made, or use the android colors

  • PESfcs .

    How to change the blue click color of the upper bar button? any one can help with this? Thanks

  • Thouseef

    Hi Ravi Tamada, Very nice tutorial. Could you please tell me that how to use sub menus in this sliding menu.. If possible kindly send me one example. This is my mail ID: thouseefsulthan@gmail.com
    Kindly help me as soon as possible..(Anyone can help)

  • hello Rivi Tamada, I love your web so much!! And i tried this code and want to have a picture header on the drawer. I have put one photo on the position(0) now,by add the following code in MainActivity, inside oncreate function(also with header.xml)
    **
    View header=getLayoutInflater().inflate(R.layout.header,null);
    mDrawerList.addHeaderView(header);

    **

    however,in the function displayView(int position), i wish i could click the header and show another fragment,so i add the following code inside the switch of function displayView

    **
    case 0:
    fragment =new HeaderFragment();//******error this line
    break;

    **
    but it has an error with command””change type of fragment to HeaderFragment””

    if anyone encounter this kind of problem, either, share your solution with me, please><
    Thank you

  • Tugsbayar

    how to open/close drawer on custom button?

    • Nuclominus

      just create observer for this button and Slider. In slider class declare update methode for observer and write mDrawerLayout.openDrawer(mDrawerList); – Profit ^^

  • Reza

    Hi guys,

    Thank you for this awesome tutorial.
    here is my question:

    Is there any why that we can use this code on Android 2.1+ ?

    Thank you

    • youming2007

      Because ActionBar was introduced in Android 3.0. If you want to run on earlier platforms, you can use the support version for ActionBar and Fragment also.

  • Mihaela

    Nice tutorial! I have a question: how to pass data between two fragments? I have an app that after you enter on a fragment I press on a button and open another fragment.I want to pass some data between this 2 fragments….

  • Albert

    I’m having a problem in the “@color/…..” it gives me an error. I’m doing it using Eclipse-ADT. Thanks for the help.

    • Jonny

      Create a file called ‘color.xml’ in the ‘values’ folder and put this;

      #fff

      #303030

      #992416

      #272727

      #626262

      #c5c4c4

  • Anand Kadekar

    HI how can I display customized expandable List view on selection of list item in the above example? I tried it with ExpandableListFragment but can not get success. Help me please.

  • Jeeten Parmar

    how to make it supportable in api 8 ?

  • Pankaj Kumar Barik

    Hello Ravi..Currently I am working as an android developer..I am new to android..Actually i am having some problems in integrating facebook into an android app for sharing images…I have gone through your post related to the integration of facebook..but it does not share images…so if u could help then i ll be thankful….

  • Michael Obi

    When the device is rotated the fragment title goes back to the Application name. Only bug i found

  • Lou S

    Is anyone else having problems with the displayView() method? I am getting “Type mismatch: cannot convert from HomeFragment to Fragment”. I am using ActionBarSherlock.

    • KC

      Couple of tips:

      1. Make sure you created a HomeFragment.class. Make sure that class implements “Fragment” from android.app.Fragment

      At the bare minimum, it should have a onCreateView() method.

      2. Make sure you are calling it exactly like in the code.

      I.E.

      fragment = new HomeFragment();

  • Gianni

    I have troubles with die onClickListener, anyone else? I don’t get an error. The SlideMenu just close but no other activity/fragment opens. In the debugger mode in Eclipse I found out that the code never goes to the Clicklistener when i tap on the menu. How can i solve this?

    • DEV

      Me too

  • Ranjith Kumar

    ravi bro is it possible to implement this slider menu for ginger bread OS?

    regards ranjithstar256@gmail.com

  • Oni

    Is it possible to use this menu to display items from a json?

    regards

  • Ranjith Kumar

    guys how to add submenus in the slidingbar listview items?? any help? 🙂

  • harish

    i’m integrating both slidemenu and expandablelistview but it is throwing exception at getChildrenCount().could you please help me solving it..(both of your examples i’m trying to integrate)

  • Pranav Lathigara

    is it possible to implement in android 2.3.6 version..?

  • Rıdvan

    Ravi can you share source code for 2.3 verison???

  • Hi Ravi,

    Your sample source is nor working on tablet.
    Crash whenever open app. Please check logcat below.

    05-20 14:34:59.250: E/AndroidRuntime(10376): FATAL EXCEPTION: main

    05-20 14:34:59.250: E/AndroidRuntime(10376): java.lang.NoSuchMethodError: android.app.ActionBar.setHomeButtonEnabled

    05-20 14:34:59.250: E/AndroidRuntime(10376): at info.androidhive.slidingmenu.MainActivity.onCreate(MainActivity.java:87)

    05-20 14:34:59.250: E/AndroidRuntime(10376): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1050)

    05-20 14:34:59.250: E/AndroidRuntime(10376): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1782)

    05-20 14:34:59.250: E/AndroidRuntime(10376): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1834)

    05-20 14:34:59.250: E/AndroidRuntime(10376): at android.app.ActivityThread.access$500(ActivityThread.java:122)

    05-20 14:34:59.250: E/AndroidRuntime(10376): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1027)

    • Baloshi69

      hey have you find any solution

  • Nice work! Is it possible to load a FragmentActivity in FrameLayout instead of Fragments?

  • Ahsan Shafiq

    How can i hide ic_launch icon from action bar

  • utsav

    Howto change the transparency level of the bacground

  • krish

    Hii Ravi u done a good job.

  • Marco Cubadda

    Hi Ravi, good job! I have a question for you. Is it possible to alternate fragments and activities in the MainActivity of the Navigation Drawer? I mean using both fragments and activities

  • purushottam dahal

    How can i add push notification in this app.?
    Please help me…..

  • puru

    How can i change the actionbar color?

  • Amit Jayaswal

    how can we make it for the API level 8 ??? It’s not working with lower API level.

  • Laith

    the source code cant be download !

  • Steve46wlf

    How can I start one of the fragment of the navigation drawer list from an activity that I created in the app?
    Thanks

  • Works perfectly for me, thanks for the great tuto !

    • baloshi69

      bro… can you give me drawer manifest cods… its giving Runtime error cus i don’t add any thing in manifest… i don’t know wht to add.

  • Shahnewaz Khan

    Did anyone else have problems with AVD displaying the drawer properly?

  • Noufal

    i cannot set getSupportActionBar().setDisplayHomeAsUpEnabled(true); instead of activity i am extends to a fragment.how i setup setDisplayHomeAsUpEnabled() as true

  • Aleria

    hello sir..
    can i get a source code for fragment and tabs layout with swipeable view..
    it’s like a BBM for android source code..
    thanks sir

  • andri kristiawan

    How to add webview in fragment

  • samphors

    Hi My name’s CHHEAN Samphors, I am a IT student, and now I have a project from my Teacher to do , it is about webview, so i try to use your code and it work only new android version , so could you tell me if I want older version support with Navigatoin Drawer.

  • sanjay kumar Barfa

    hi ravi i want 4 different navigation drawer from left side. i have 4 different background button. based on user choice drawer should be appear when user click 1st home button drawer should be appear. when user click 2nd button another drawer same side should be appear as well as 3rd and 4th button. 3rd have another drawer and 4th have another drawer

  • zsurzsalaszlo

    Hey, I’m having problem using some custom colors in the color.xml. Colors having correct format look different then the ones I created in Inkscape. Does somebody have this problem?

    • baloshi69

      hey… its not running in environment it ging Runtime exception….. its because i have add anything in manifest… can you help me wht should i add… plz can you give me your manifest screenshot

    • baloshi69

      sorry… i mean i haven’t add any in manifest…

  • baloshi69

    hey… wht should we add in manifest its giving me Runtime Errer

    • jaydeep

      you can write log or you can handle exception and print error message on toast.

  • Guest

    i have a problem in @color/list_divider, where can i get the color resources, because i haven’t, i use Intellij Idea as my editor.. anyone can help me?

  • Guest

    Hi, i have a problem in DrawerLayout and ActionBarDrawerToggle, should i import something? and what is that?

  • Diego Sagrera

    Anyone found a way to update the counter programmatically?

    • Sayaji

      Also i need this. If you done this then help me please.

      • Diego Sagrera

        I didn’t try this Sayaji, but maybe this would do the trick. Add a new String parameter to:
        navDrawerItems.add(new NavDrawerItem(HERE, navMenuTitles[0],….

        Then create the “id” String variable in “NavDrawerItem” class and also getters and setters for it.

        Update the method to match new settings:

        public NavDrawerItem(String id, String title, int icon, boolean isCounterVisible, String count){
        this.id = id;
        this.title = title;
        this.icon = icon;
        this.isCounterVisible = isCounterVisible;
        this.count = count;
        }

        Then I think it’s a matter of doing something like a setText for that id.

        Hope it helps.

  • jaydeep

    In sliding menu fragment is required can i use layout without fragment?

  • Akshay

    Amazing tutorial..! Simply awesome

  • Nima Shafiei

    Hi,ur tutorial in very nice and cool.
    but i have a probem,i want my slider on the right(for persian language)

    plase help me…!!!
    thanks

  • hunterharada

    where should i place the fragment_home.xml? i have a problem with that, and also i can’t use SlideMenuClickListener when i want to use it for instance.. anybody can help me?

    • Nima Shafiei

      fragment_home.xml on layout folder.

      can u explain ur second problem..?

      • hunterharada

        my question is in this code:

        /** mDrawerList.setOnItemSelectedListener(new SlideMenuClickListener()); **/

        it said that SlideMenuClickListener cannot be applied in AdapterView..

        • Nima Shafiei

          check ur “SlideMenuClickListener” and “displayView” metods.
          if u add new fregment,u should define it on “navDrawerItems”.

          copy ur code on here.

          • hunterharada

            i’ve tried to run that project, it has no error, but it’s stop working when i run it on my device, when i look at the logcat, it has a problem in MainActivity in SlideMenuClickListener.. it said caused by java.lang.NullPointerException in MainActivity.. have you ever see that problem?
            Also, nothing says that SlideMenuClickListener dan displayView method must be define on navDrawerItems,, if it must be, how to make it? Does NavDrawerItem just contain constructor, setter getter?

  • Guest

    guys, i have a problem in my project, it said :
    Error:android-apt-compiler: Cannot create directory: C:UsersJOSHIE.IdeaIC13systemcompile-server_temp_android_apt_output6096636159062647453tmp

    even i can’t understand what’s wrong with it

  • Guest

    sir, i have some error like :

    Error:android-apt-compiler: [Liquid_Social_Manager_Extra] resdrawable-hdpilist_selector.xml:0: error: Resource entry list_selector is already defined.

    Error:android-apt-compiler: [Liquid_Social_Manager_Extra] resdrawable-hdpilist_selector.png:0: Originally defined here.

    anyone can give me expalin about that and solution about that?

    • Kyle

      Sometimes it helps to actually think about what computer is telling you and not be lazy and just ask for help.

  • hunterharada

    why this code not running well in my device, it’s stop working.. but no error..

  • purushottam dahal

    Please help me about clicklistener in home fragments..?

  • hunterharada

    how to make that this activity is not start first, there is an other activity before..

    • Change it in your AndroidManifest.xml file

      • hunterharada

        ok thanks!

      • Nehal Goyal

        hii

        I have add button in my fragment, when I click on that button I want new activity should be open…

        there is no error in my code but my app is getting crash.
        i m using ur slidermenu example in this.. My main activity is slider menu..

        here is the code :

        package info.androidhive.autosms;

        import android.app.Fragment;

        import android.content.Intent;

        import android.os.Bundle;

        import android.view.LayoutInflater;

        import android.view.View;

        import android.view.ViewGroup;

        import android.widget.Button;

        public class BirthdayFragment extends Fragment {

        public BirthdayFragment(){}

        @Override

        public View onCreateView(LayoutInflater inflater, ViewGroup container,

        Bundle savedInstanceState) {

        View v = inflater.inflate(R.layout.fragment_birthday, container, false);

        Button button1 = (Button) v.findViewById(R.id.button1);

        button1.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {

        Intent intent = new Intent(“info.androidhive.autosms.setup”);

        startActivity(intent);

        }

        });

        return v;

        }

        }

  • Ludo

    Hi, thanks for this awesome tutorial!
    My main fragment is a ListFragment and I’d like to enable Multichoice mode. I tried to simply activate it on the XML list view but it doesn’t work. Do you have any clue?

  • HobbyDev

    Just want to say big THX for this post.

  • Pravesh Choudhary

    I have an activity previously created that I want to open after clicking the Home button of NAvigation Drawer. But Navigation Drawer only deals with Fragments. How can I do it ?

  • Anil

    how to move actionbar with drawer like facebook???

  • dns

    Hy Ravi How to Change List item height dynamicly, iwant to make one item for user image profile like google +

    • dns

      i want to have cover photo inside the item

      • alex

        hi am too trying the same you got any idea on this

  • dns

    Hy Ravi How to Change List item height dynamicly, iwant to make one item for user image profile like google +

    http://www.androidhive.info/wp-content/uploads/2013/11/sliding-menu-example-applications.jpg?5fd5e4

  • mr.TS

    Great tutorial, how can i do slide down like this? I want to slide from top to middle.

    • Navigation drawer works only left -> right or right -> left. For your requirement may be you have to build a custom widget.

      • Don

        sir how to make it right -> left.

  • Ashish Kumar Gupta

    what can be done if i want the backscreen to make slide with sliding drawer,i.e,when drawer slides in an specific amount the backscreen also slides towards right upto the same extent

  • Ashish Kumar Gupta

    In the MainActivity.java file: “fragment = new CommunityFragment(); i m getting this error Type mismatch: cannot convert from CommunityFragment to Fragment

  • Eagel

    nice tutorial,but i have an extra problem:how to remove the counter on the drawer when we click the menu?

  • Anggrayudi H

    Nice… But, how to add the Header and set the clickable(false);?

  • SD

    how to add new item in list and action on case 6.

  • Syarif Ibnu Miftahudin Al-Dami

    Nice tutorial and It works great. But I have a problem.
    I got each drawer list item has a huge value of height that looks inappropriate while yours looks great and I don’t know how to fix this. Please help me.

  • NamHV

    Can you tell me how to add Tabhost inside Fragment (ex: HomeFragment)

  • mohsen

    nice tutorial , i need use it on android 2 , and support actionbar using android.support.v7.app.ActionBarActivity on MainActivity how can i load fragment ?

  • Ashish Kumar Gupta

    how to implement flyout menu in ur example

  • Rad

    Hi, i have a problem in DrawerLayout and ActionBarDrawerToggle, should i import something?

    • Edwin

      you have to add the support library, if you are using eclipse then right click on project -> Android Tools -> Add Support Library.. if you are using android studio then right click on your project then click on “Open Module settings” then click on “app” then goto “dependencies” then click on the plus icon and choose the suppor library v4 then click add

  • Rad

    import android.support.v4.app.ActionBarDrawerToggle;
    import android.support.v4.widget.DrawerLayout;

    also these two lines also show error… plz help!!

    • You need to add android supportv4 jar. Right click on project -> Android Tools -> Add Support Library

  • rebecca aneeq

    Hi, Great tutorial Ravi. I tried for more than week to make it to work on android 2.2, but I failed. Will you please tell me that whether this will work on android 2.2, I also tried sherlockactivity, but it also craches on 2.2. Thanks in advance. May you live long 🙂

    • Govt. High School Gajjumatta L

      Yes same problem here. Please help

    • Thursdae

      Why are you trying to make it work on a version thats 0.7% of all android devices????….

  • Rogerio

    Hi Ravi, great tutorial (as always!! ;D). I want to mix Sliding Menu with your other tutorial about Facebook like Custom Listview using Volley.Can you produce a tutorial about it, or show us the path??

    Thanks in advance!!

    • Its easy. Just add the code from facebook tutorial into navigation drawer project.

      • Alan Lee

        Hi @ravi8x:disqus ,I’m beginner in Android, When I combine the code, the following line will get error, can you tech me how can I fix it, thank you so much

        listAdapter = new FeedListAdapter(this, feedItems);

  • jasser

    this is amazing as always. best tutorial i have ever found on the web.
    works like a charm.
    thanks a looooooooooooooooooooooooooooooooooooooooooooot

  • gopal singh

    sir i want to add image in the action bar

  • arun kumar

    Thanks Ravi.I think this is best tutorial.I like this tutorial more than which is on developer.android.com.One think i am concern that this above code is for only 3.0 and above version.Can u modified this code for android 2.1 and above?

    • Hi Arun,

      You need to use AndroidSupportLibrary to support < 3. Although there is very less percentage of devices are there which runs on 2.x

      • arun kumar

        According to android distribution list, android 2.2 android 2.3.3 is total 7% of market

    • nandhini devi

      how about using sherlock ?@disqus_5vcQAV7yMO:disqus

      • arun kumar

        In current android framework support library is exist which is supporting actionbar till 2.1 version. I have not used sherlock library.

  • Vihaan

    Hi Ravi, Thanks for this great tutorial. I have made my app after following your tutorial and later I have realized that you have created a new fragment everytime. In my app new instance of the fragment fire s async task , get the data and display’s it to the user but this happens on every click. I m thinking of optimizing it such that a fragment will only be created once and shown again when the user clicks on the sliding menu instead of getting created and loading data again. Do you have any idea how that can be done ? Thanks.

  • nandhini devi

    @ravi8x:disqus hy is it possible to combine tablayout with swipe in this ?

  • Ernani De S. Thiago

    Hello, I was trying to build my project with this interface (side menu bar) and, well I downloaded the example project and run it, everything was ok, but when I tryied to “manage” the xml elements of one of the fragments, for example create a button and set a listener to it in fragment_home.xml. I couldn’t find where to put it in the java code….can somenone help me?

    • Vikas Mittal

      Firstly – Your Fragment class should implement View.OnClickListener
      (for eg. – public class HomeFragment extends Fragment implements View.OnClickListener)

      It will ask you to ‘Add Unimplemented Methods’ – i.e. public void onClick(View v)

      In OnCreateView Method – find the Button
      btnDetails = (Button) rootView.findViewById(R.id.btnDetails);

      And do, btnDetails.setOnClickListener(this);

      Then goto the onClick Method (as generated above)
      Probably use Switch Case (if you have more than 1 button)

      switch(v.getId()){
      case R.id.btnDetails:

      //Your code here
      break;
      }

  • Illuminate

    Hi Ravi, i have tried to sign up but i dont get an email notification

  • I did everything exact the same but im getting a “unfortunately, has stopped.” error
    I dont understand the description in my log, please help:

    30429-30429/org.imarks.selectieveluistertest E/AndroidRuntime﹕ FATAL EXCEPTION: main

    Process: org.imarks.selectieveluistertest, PID: 30429

    java.lang.RuntimeException: Unable to start activity ComponentInfo{org.imarks.selectieveluistertest/org.imarks.selectieveluistertest.MainActivity}: android.content.res.Resources$NotFoundException: String array resource ID #0x7f090001

    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2596)

    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2653)

    at android.app.ActivityThread.access$800(ActivityThread.java:156)

    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1355)

    at android.os.Handler.dispatchMessage(Handler.java:102)

    at android.os.Looper.loop(Looper.java:157)

    at android.app.ActivityThread.main(ActivityThread.java:5872)

    at java.lang.reflect.Method.invokeNative(Native Method)

    at java.lang.reflect.Method.invoke(Method.java:515)

    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:858)

    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:674)

    at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:132)

    at dalvik.system.NativeStart.main(Native Method)

    Caused by: android.content.res.Resources$NotFoundException: String array resource ID #0x7f090001

    at android.content.res.Resources.getStringArray(Resources.java:483)

    at android.content.res.XResources.getStringArray(XResources.java:683)

    at org.imarks.selectieveluistertest.MainActivity.onCreate(MainActivity.java:59)

    at android.app.Activity.performCreate(Activity.java:5312)

    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1111)

    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2552)

    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2653)

    at android.app.ActivityThread.access$800(ActivityThread.java:156)

    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1355)

    at android.os.Handler.dispatchMessage(Handler.java:102)

    at android.os.Looper.loop(Looper.java:157)

    at android.app.ActivityThread.main(ActivityThread.java:5872)

    at java.lang.reflect.Method.invokeNative(Native Method)

    at java.lang.reflect.Method.invoke(Method.java:515)

    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:858)

    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:674)

    at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:132)

    at dalvik.system.NativeStart.main(Native Method)

    • Clean the project and build it again.

      • Thanks, i did not rebuild the project but thought about what i else i changed to the project. seems i forget to create the strings for other languages then my native language. Thanks man, you tutorial and help are very usefull, very optimal code and easy to understand 🙂

  • zeljko

    This is by far the worst way of developing I have ever seen. Write more do less doctrine is specific for developing Android content . This makes a lawnmower a fucking peace of electronic art compared to Android… Android development is so shitty that it resembles to hunting a lion by using retarder mice as a haunt dog… THE HTML version 1 was better than this… The best practice for developing in Android and avoid nervous brake down is by using the WebView. Anything else will make you lose your hair…

    • Monkey

      I agree. This is a horrible development platform. As for this site, I have downloaded several examples from this site and have not managed to get one to work without errors. It would be nice to include more detailed instructions to use them. Oh well, my search for a site with simple, easy to understand tutorials continues. If anyone has any suggestions please post.

  • Hi, i am kind of a new here.
    Could you explain how the second argument for the getResourceId() function works …i:e why is ‘-1’ as the second argument. I know it has no relevance since the resources are already defined. But it would clarify my doubts of that function.

    • Nixter

      -1 means default value if the requested resource not found (check API)

  • David

    Hi, I’ve tried to combine this and your imagelistview. Everything works fine else than by prssion on items of sliding menu, nothing happens (it closes) Can you help me please? Thanks

  • Mayssam Mazloumi

    Hi there,
    If I have more option in my drawer ( like dynamic categories), what should i do with fragment?!
    I can’t create a fragment for each category because categories are variable and can be add later.
    What’s your solution for this?! please help me

  • Sayaji

    Hi Ravi, Thanks for this great tutorial. How to update counter of menu item in this tutorial. Is this possible?

    • Yes you can. You have to update the counter value in the array which is used for navigation drawer adapter. Then you should call notifyDatachanged on the adapter.

      • Karthi9474@gmail.com

        hai ravi great tutorial Thanks, i need how to add header image and Text in Navigation drawer and how to press back button in new community fragment to home fragment…

        • You can add header image by following below tutorial

          http://www.androidhive.info/2015/04/android-getting-started-with-material-design/

          To detect the back press, have a variable and store some value which denotes the home screen. When user selects the navigation drawer item change this variable value with something else. When user presses the back button check the value of the variable and load the appropriate fragment home or other fragments.

          • Karthi9474@gmail.com

            Thanks Ravi….

  • abhilash

    is this support Android 2..3 API10?

  • daniel

    i wanna to do webview on each page ho i can do that i try but is not working?

  • sean

    Hey Ravi i like the tutorial, quick question though how could i make a one of the items in a list launch a Preference Screen?

  • imZEH

    do you have lots of icons that looks like ? can i have one Like PSD file ..

  • prabhakar

    hello guys

    I am trying to implement this code but Activity not started

    the logcat show following error

    07-26 06:13:41.167: E/AndroidRuntime(2219): FATAL EXCEPTION: main

    07-26 06:13:41.167: E/AndroidRuntime(2219): Process: com.easy.menu, PID: 2219

    07-26 06:13:41.167: E/AndroidRuntime(2219): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.easy.menu/com.easy.menu.MainActivity}: android.view.InflateException: Binary XML file line #14: Error inflating class android.widget.ListView

    07-26 06:13:41.167: E/AndroidRuntime(2219): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)

    07-26 06:13:41.167: E/AndroidRuntime(2219): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)

    07-26 06:13:41.167: E/AndroidRuntime(2219): at android.app.ActivityThread.access$800(ActivityThread.java:135)

    07-26 06:13:41.167: E/AndroidRuntime(2219): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)

    07-26 06:13:41.167: E/AndroidRuntime(2219): at android.os.Handler.dispatchMessage(Handler.java:102)

    07-26 06:13:41.167: E/AndroidRuntime(2219): at android.os.Looper.loop(Looper.java:136)

    07-26 06:13:41.167: E/AndroidRuntime(2219): at android.app.ActivityThread.main(ActivityThread.java:5017)

    07-26 06:13:41.167: E/AndroidRuntime(2219): at java.lang.reflect.Method.invokeNative(Native Method)

    07-26 06:13:41.167: E/AndroidRuntime(2219): at java.lang.reflect.Method.invoke(Method.java:515)

    07-26 06:13:41.167: E/AndroidRuntime(2219): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)

    07-26 06:13:41.167: E/AndroidRuntime(2219): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)

    07-26 06:13:41.167: E/AndroidRuntime(2219): at dalvik.system.NativeStart.main(Native Method)

    07-26 06:13:41.167: E/AndroidRuntime(2219): Caused by: android.view.InflateException: Binary XML file line #14: Error inflating class android.widget.ListView

    07-26 06:13:41.167: E/AndroidRuntime(2219): at android.view.LayoutInflater.createView(LayoutInflater.java:620)

    07-26 06:13:41.167: E/AndroidRuntime(2219): at com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:56)

    07-26 06:13:41.167: E/AndroidRuntime(2219): at android.view.LayoutInflater.onCreateView(LayoutInflater.java:669)

    07-26 06:13:41.167: E/AndroidRuntime(2219): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:694)

    07-26 06:13:41.167: E/AndroidRuntime(2219): at android.view.LayoutInflater.rInflate(LayoutInflater.java:755)

    07-26 06:13:41.167: E/AndroidRuntime(2219): at android.view.LayoutInflater.inflate(LayoutInflater.java:492)

    07-26 06:13:41.167: E/AndroidRuntime(2219): at android.view.LayoutInflater.inflate(LayoutInflater.java:397)

    07-26 06:13:41.167: E/AndroidRuntime(2219): at android.view.LayoutInflater.inflate(LayoutInflater.java:353)

    07-26 06:13:41.167: E/AndroidRuntime(2219): at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:290)

    07-26 06:13:41.167: E/AndroidRuntime(2219): at android.app.Activity.setContentView(Activity.java:1929)

    07-26 06:13:41.167: E/AndroidRuntime(2219): at com.easy.menu.MainActivity.onCreate(MainActivity.java:46)

    07-26 06:13:41.167: E/AndroidRuntime(2219): at android.app.Activity.performCreate(Activity.java:5231)

    07-26 06:13:41.167: E/AndroidRuntime(2219): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)

    07-26 06:13:41.167: E/AndroidRuntime(2219): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)

    07-26 06:13:41.167: E/AndroidRuntime(2219): … 11 more

    07-26 06:13:41.167: E/AndroidRuntime(2219): Caused by: java.lang.reflect.InvocationTargetException

    07-26 06:13:41.167: E/AndroidRuntime(2219): at java.lang.reflect.Constructor.constructNative(Native Method)

    07-26 06:13:41.167: E/AndroidRuntime(2219): at java.lang.reflect.Constructor.newInstance(Constructor.java:423)

    07-26 06:13:41.167: E/AndroidRuntime(2219): at android.view.LayoutInflater.createView(LayoutInflater.java:594)

    07-26 06:13:41.167: E/AndroidRuntime(2219): … 24 more

    07-26 06:13:41.167: E/AndroidRuntime(2219): Caused by: android.content.res.Resources$NotFoundException: File res/color/primary_text_dark.xml from drawable resource ID #0x1060001

    07-26 06:13:41.167: E/AndroidRuntime(2219): at android.content.res.Resources.loadDrawable(Resources.java:2096)

    07-26 06:13:41.167: E/AndroidRuntime(2219): at android.content.res.TypedArray.getDrawable(TypedArray.java:602)

    07-26 06:13:41.167: E/AndroidRuntime(2219): at android.widget.ListView.(ListView.java:158)

    07-26 06:13:41.167: E/AndroidRuntime(2219): at android.widget.ListView.(ListView.java:142)

    07-26 06:13:41.167: E/AndroidRuntime(2219): … 27 more

    07-26 06:13:41.167: E/AndroidRuntime(2219): Caused by: org.xmlpull.v1.XmlPullParserException: Binary XML file line #18: tag requires a ‘drawable’ attribute or child tag defining a drawable

    07-26 06:13:41.167: E/AndroidRuntime(2219): at android.graphics.drawable.StateListDrawable.inflate(StateListDrawable.java:181)

    07-26 06:13:41.167: E/AndroidRuntime(2219): at android.graphics.drawable.Drawable.createFromXmlInner(Drawable.java:937)

    07-26 06:13:41.167: E/AndroidRuntime(2219): at android.graphics.drawable.Drawable.createFromXml(Drawable.java:877)

    07-26 06:13:41.167: E/AndroidRuntime(2219): at android.content.res.Resources.loadDrawable(Resources.java:2092)

    07-26 06:13:41.167: E/AndroidRuntime(2219): … 30 more

    please help how to solve this.
    Thank You:)

  • Vikas Mittal

    Hello Ravi,

    Thank you for the code – it works fantastically smooth 🙂
    I have a question – (somebody did asked this question earlier but somehow I couldn;t implement it).

    Pick any of the fragments – say HomeFragment. I have used a button there for certain activity. Now once the activity is successfully completed I would like to change the counter no. of the “Communities” Item – please suggest!!

    • Hi Vikas,

      Try to change the counter value of one of the items in navDrawerItems and call notifyDatasetChanged on adapter.

  • quinn91

    How to integrate with action bar ? in this link http://www.androidhive.info/2013/11/android-working-with-action-bar/ . im newbie.

  • Sayaji

    Hi Ravi, ,When opened camera from any page/fragment then MainActivity Stopped and destroyed. And Application open first page.

  • Guest

    Hi Ravi, my navigation drawer only shows up when I swipe from left. It does not show up on tapping the action bar icon. Any idea what i might be doing wrong ?

    • Check whether you added these lines are not
      getActionBar().setDisplayHomeAsUpEnabled(true);

      getActionBar().setHomeButtonEnabled(true);

  • alex

    Hi Ravi, I type my email into subscribe input box, and click subscribe. It said it has sent an email to me. But after I waiting for a while, there is no email sent to me. So I can’t download the source code

    • AndroidBot

      Check on spam

      • alex

        I found it! Thank you!

  • Aditya Thakar

    Great tutorial … Thanks Ravi…

  • Hardik Patel

    Hii Ravi Thanks..Nice Tutorial.. i have one problem in 2.3.. at top its remain some space .. and in 4.2 its perfect so whats the problem in 2.3?
    please reply

  • Chandan Dwivedi

    hi Sir,
    Thanks for great tutorial but i am looking for tutorial in which swipe-able tab view is implemented with navigation drawer. If you can post this tutorial soon then it would be more appreciated…….thanks in advance.

    • Using swipable tabs with Navigation drawer is not suggested by android. You should use only one.

      • nima

        but what about google paly?! it use both of them! i need it very much please can you help me?

  • Tony Joseph

    Hi Sir,

    I have a doubt using fragments in this project. I have created a custom listview in one of the fragments which you have created. that is in the find people fragment, I have created a custom listview for displaying elements as a listview. Now I have also overrided onListItemClick for that custom listview. Now when I click on any element in the list, I need to move to another screen showing the details of the selelcted element. For that I have created a fragment as per your instructions and created a layout file for it also using the help of your article. But I have a doubt on how to navigate from one fragment to another upon clicking a custom list element. Can you please help me out. I have searched google and found out a way to navigate from one fragment to another. But it is showing an error upon clicking the listview element like this:
    java.lang.IllegalArgumentException: No view found for id 0x7f0a0014 for fragment ImportantNumbersFragment{537f930c #1 id=0x7f0a0014}. The code which I have used for navigating from one fragment to another is this:
    Fragment ImportantNumbers=new ImportantNumbersFragment();
    FragmentTransaction ft=getFragmentManager().beginTransaction();
    ft.replace(R.id.fragment_container,ImportantNumbers);
    ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
    ft.addToBackStack(null);
    ft.commit();

    In the xml file of the new fragment, I have given this code:

    Can you please help me out.. If this is not the way to move from one fragment to another, then can you please show me how to do it. Please help me..

  • Harman Preet

    Hi great tutorial, Thanks
    I am stuck in another problem, How can i place an image instead of app icon in left corner of actionbar such that if i click on image navigation drawer opens up. Something like Times of India app’s main activity. If you can provide some code or link to the tutorial that would be of great help. Thanks again.

  • Rendy Setya Pratama

    Thanks for Great Tutorial 🙂

  • Monisha

    Hi.. How can i set this slider menu as default(its visible always)??
    Thank You

  • achin verma

    HI
    I have made my app after following your tutorial and later I have realized that you have created a new fragment everytime. In my app new instance of the fragment fire s async task , get the data and display’s it to the user but this happens on every click. I m thinking of optimizing it such that a fragment will only be created once and shown again when the user clicks on the sliding menu instead of getting created and loading data again. Do you have any idea how that can be done ? i mean how can i save the fragment ?

    • ssougnez

      I’m facing the same issue but I think it could easily be solved by creating an HashMap that you populate when the user click on menu item. When he clicks, you check if an element exists in the HashMap with that key (the index), if it does, you return it, if not, you create it and add it to the HashMap. Gonna try that, I’ll post another comment if this is not a good solution.

  • Runesh

    Hi dude……….Its an awsome tutorial……

    I want to use activity instead of fragments…..So if i call an new activity the navigation drawer is not working…..Plzz solve this problem……And even tell me how to call navigation drawer from each activity

    • Why do you want to use Activity when Fragment provides better options?

      • Dario Mirkovski

        Ravi Tamada, I know this might sound crazy, but I am stuck at inserting a TextView at the activity_main.xml of the above tutorial. When ever i want to insert TextView in the XML, it does not show. I’ve tried creating a new LinearLayout like this:

        Where should i put a text view so it does show up on the screen?

        Thank you.

        Dario

        • Its because you main activity view will be hidden always as we are loading HomeFragment on application onCreate by calling displayView(0);

          May be you need to add your TextView in home fragment layout instead.

          • Dario Mirkovski

            I wished that was the issue but it is no. I commented that line off as once it was chosen at default (I am working with activities) goes into loop and never ends. I might take that look at that to check it out. Seems not a lot options though. Will see it later. Thank you.

          • Okay.

      • Runesh

        Im a newbie , so what ever codes that work on Activities shows error is Fragments… so i wanted to use activities.

        Thank you @ravi8x:disqus

        • Replacing activity with fragment is too easy. Just read the differences b/w them.

          • Runesh

            Can you suggest me any Links……..

          • kumar

            By using only activities (like HomeActivity.java) can you write code and also in HomeActivity.java there are four intents that means another 4 subactivities in these subactivities also navigation toggle should present

    • Dario Mirkovski

      Well, I did the thing you say:

      1) Every activity must extends the DrawerHome (where you create the drawer)

      2) When you create every other activity, you must use this code:
      LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
      View contentView = inflater.inflate(R.layout.XMLFILE, null, false);
      mDrawerLayout.addView(contentView, 0);

      3) When switching activities uses this code:

      private void displayView(int position) {
      // update the main content by replacing fragments
      Intent intent = null;

      switch (position) {
      case 0:
      intent = new Intent(this, NewActivity.class);
      break;
      case 1:
      intent = new Intent(this, NewActivity.class);
      break;
      default:
      break;
      }
      startActivity(intent);

      However, please listen what @ravi8x:disqus said. Fragemnts are mini activities. However, I already have done most of my activities and need a drawer. This is the reason why i did not switch everything to Fragments.

      Good luck, anyways.

      • Runesh

        thanks @dariomirkovski:disqus

      • kumar

        How to extend the drawerhome
        can you write code for this

        • Dario Mirkovski

          Well finally I have listen to author and converted all my activities into fragments. And now I only have onr Activity which loads the drawer and different fragments which only replace the content. Nothing more than what the tutorial says. And yes, everything is much smoother and I love the transition.

          My advice: Forget many Activities. Switch to fragments. Awesome.

          • kumar

            This is my situation:
            By using only activities (like HomeActivity.java) can you write code and also in HomeActivity.java there are four intents that means another 4 subactivities in these subactivities also navigation toggle should present

          • Dario Mirkovski

            I guess you need to work that part by your self. And if you wanna see the drawer in all the activities you must DrawerHome, then HomeActivity extends DrawerHome, SubActivity extends HomeActivity and so on. But I guess at a point you will hit the wall. But never have experience with so much activities.

          • kumar

            first of all thanks for your replies
            suppose my subactivity is MsgActivity and i wrote

            public class MsgActivity extends Activity you are saying you have to extend DrawerHome how to do that can you write?

            we have to use 2 extends?

          • Dario Mirkovski

            If you followed the tutorial I guess DrawerHome extends Activity and if MsgActivity extends DrawerHome that it inherits all classes extended by DrawerHome. No need for extending two classes.

          • kumar

            i think you already tried no by using activities?
            can you send me the code?

          • Dario Mirkovski

            Well all that I have to say, said in the previous comment. So I guess you fix it alone.

  • ssougnez

    Waw… This tutorial is just awesome… Congrats. Now I’m gonna read the one concerning the connection with the REST API. If the quality of that one is equal to the quality of this one, my app will be done tomorrow 😀

    Thanks a lot

  • Meysam

    This Tutorials is the best.
    I want to use ListView in fragment_pages.xml And I initialized to PageFragment.java
    How can I do this?
    Please write me an example with code.
    Thanks.

  • Abhilash .K.V

    hai This tutorial is just awesome…

    how to work this example in Api level 8, android 2.2

  • Waheed

    Its amazing… but unable to download the code. pls guide

    • What is the problem you are facing while downloading?

      • waheed

        it doesn’t start! Also, since YouTube is banned, I cannot watch the demo video, can you please share the link so I can watch using proxy.

        • Even youtube is blocked me right now 🙁 but the code you can download by pressing DOWNLOAD CODE button at the top.

          • Waheed

            I have managed it without video and code, it is working perfectly 🙂 I need a favor, can you please guide how to have WebView in fragments. I want to add webview in all the drawer fragments. I tried but it is not working.

  • Hi Ravi Sir
    Its an awesome tutorial……

    can i get a expandable-sliding-menu-using-navigation-drawer using fragments only……
    hemanth.somaraju@gmail.com

  • Punit

    Hi thnx for the demo
    but i have a query regarding when we go to detail page, this humberger menu icon changes to back button. if you notice in gmail app. when you are on detail page of app and you open the drawer, back button changes to humberger and when you close it , it become back again. how to manage this . i need help !!

  • Punit

    if you have a gmail app.. then open a mail .. then open the drawer from left you will see whole actionbar is changed ( bck button become humberger and other ) what i am asking is that ?

  • Nick

    Ravi,

    Once again a great tutorial. It works awesome and will definitely be useful. One question I have is…if I wanted to show this on multiple activities, how would I go about doing so? As you have it, the app only stays on one activity and opens fragments. On the click of a Menu Item, I would like it to move to another activity and still have the menu available for use. ANy ideas? Thanks

  • Yadnyesh

    i am using navigation drawer in my android app..
    Each of fragment contains async task which getting data from internet and displaying in custom list..

    But when i am switching between fragments an async task started loading data again..
    So how to save state of fragment

  • alex

    hi i want to show an profile image captured from URL in the slider menu. But it is very difficult can help on this as screen shots show a profile image name and email id

  • John

    I am new in android development and this tutorial is great! Though I was wondering, I want to display the number of rows in my table in the counter. Is that possible?

    • Yes. Check the MainActivity.java where we are setting data in navigation drawer adapter.

      navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons.getResourceId(3, -1), true, “22”))

      In the above line 22 is counter value. You can replace 22 with the number of rows in the table.

  • Joel || GetAvenue

    Great tutorial, I am a newbie in Android development,I just downloaded your code and decide to use it, but I’m stuck.
    Please how can I remove the number showing beside the Community Fragment and What’s Hot Fragment. Thanks
    Will love to get your reply quick.

    • Hi Joel,

      If you observe MainActivity.java you can find following code
      navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons.getResourceId(3, -1), true, “22”))

      In this if you remove ‘true’ parameter, the counter won’t be visible.

      • Joel || GetAvenue

        Thanks, for your help

  • fik

    sir can how i can add feature of actions bars

  • Saktian

    Hi Ravi, im using your download code but i found error only on NavDrawerItem info.androidhive.slidingmenu.model ?
    How fix this ?
    Thankyou for great tutor 🙂

  • Pawan Ratre Gurjar

    Hello Sir,

    Your all articles are awesome and very easy to understand.

    I have completed so many work by your code in my applications… Actually I am a full time .NET developer. so some time its hard to understand android code…

    can we make Navigation Drawer. menu for API 10 also…

    and is any way available where we can create an image or icon for all android devices like logo(Automatically generates in all folders)…

  • Ankit

    Hi Ravi,
    I’m using this code and its working awesome, but now due to I’m stuck here…
    Can you tell me how would i place last 2 item of my sliding list into bottom of listview.
    I don’t want to change in my activity_main.xml file to put listview and those two chilld views in a relative layout.

    Plz reply soon….

  • Ashish Tiwari

    Hello Ravi, I read this tutorial and used in my project. its working absolutely fine. In other project I need a header (Image of User and Name) just on top of Home in menu list (Like YouTube application). I tried to make layout but still not got the result. Can you suggest me what should I do?

  • Achraf

    How to display overflow in sliding menu in this exemple , when i have used menu.xml does’t work

  • waseem ahmad

    hello Ravi You Update Ur Tutorial According To U gave Image Example Above …Google+ Profile Image Above …

    Every One Is Looking For That Type Sliding Menu

  • Raam

    Thanks for nice tutorial. Instead of calling HOME fragment how do I call HOME class that extends activity (start activity intent) is making me not show the menu.

    • waseem ahmad

      u have To Extends Fragment Class ..Try To Convert in Fragment …

  • Alessandro

    Awesome tutorial!!!! Congrats!!!!

  • you_wanna_disqus?

    Awesome tutorial! I want the navigation drawer fixed in tablet view. How can I do this?

    • karathb

      Could you solve it?

      • you_wanna_disqus?

        Yes. You need to create device-size dependent values folder in res directory. 7 inch tablets use the folder values-sw600dp and 10inch tablets use the folder values-sw720dp. In those folder create an xml file named layout.xml . In the xml do this:

        true

        You are creating a boolean value and you can change it in the different layout.xml files. In the default values folder create the layout.xml file and set the bool value to false. Get this value in the activity using

        boolean isTablet = getResources().getBoolean(R.bool.tablet);

        you can also create folders for land mode and portrait mode and have different settings for different orientation.

        populateTheListView(); // here you customize the listview with adapters and stuff

        if(!isTablet)
        setupTheNavigationDrawer(); // here you will do the mDrawerLayout stuff

        Do give a feedback. 🙂

        • karathb

          sorry for late answer, i dit not notice your comment. I ended up using PanesLibrary, it supports tablet and phone design. But anyway, thanks for your reply!

  • Jaydeep Goyani

    It’s really nice work .

  • Guest

    Good tutorial.
    Is it possible to add expandable listview to the slider ?

  • roshgorg

    Hello,

    I was following the tutorial for adding a sliding menu.
    I see that, we are populating fragments based on the menu click. All the fragments have pre-populated data.

    In one of the fragments, I added a google map. It works fine for the first time, but, when I navigate to some another page, and return back to this page, it crashes, saying, some kind of permission denied. Is it having something related to using fragments and google maps ?

    Another issue that I see is, the app is taking nearly 6 MB of space.

  • Achin Verma

    Hi, i’m using this demo, How do i change the RED color of listview in navigation drawer as in your screen shot to #mycolor?

  • Dhaval

    How can I change item name at run time?
    I have an item in drawer “Turn off all Alarms”. When click on it the item should be change in “Turn on all Alarms”
    Please help as soon as possible.

    • tom

      you can change item name for example item1 to change item2

      • Dhaval

        How?

  • Thank you very much for your demo. I have used it to develop an hymn book app, but am having difficulties adding a search button, so I user can search through the navigation list item

  • Pawan Ratre Gurjar

    Hello Ravi Sir…
    I have to maintain fragments like if we press back button than last fragment come but if we use add in place of replace than the background activity also visible…So its a big overhead for me…
    How can i maintain easily…I WANT before close app always user comes at Home Fragemnt

    • Ramesh Emandi

      Maintain instance of HomeFragment in MainActivity. If you are on HomeFragment, Add to stack or else use Replace. Handle onBackPressed to pop your fragment. Use FragmentTransaction instead of FragmentManager.

      It goes somewhat like.

      // FragmentManager fragmentManager = getFragmentManager();
      FragmentTransaction trans = getFragmentManager().beginTransaction();
      if(homeFragment.isVisible() && fragment != homeFragment){
      trans.addToBackStack(fragment.getClass().getSimpleName());
      }
      trans.replace(R.id.frame_container, fragment).commit();

      • Pawan Ratre Gurjar

        Thank you sir…

        By this method i can move beteen 2 activities very well

        public void selectItem(int position) {

        FragmentManager fragmentmanager = getSupportFragmentManager();

        fragmentmanager.popBackStack();
        if(position==0)

        {

        FragementHome homeFragment = new FragementHome();

        fragmentmanager.beginTransaction().

        replace(R.id.content_frame, homeFragment).commit();

        }else if(position==1)

        {

        FragementSearch searchFragment = new FragementSearch();

        Bundle args = new Bundle();

        args.putString(FragementSearch.searchtype,”KeyWord”);

        searchFragment.setArguments(args);

        fragmentmanager.beginTransaction().

        replace(R.id.content_frame, searchFragment).addToBackStack(null).commit();

        }else if(position==2)

        {

        FragementSearch searchFragment = new FragementSearch();

        Bundle args = new Bundle();

        args.putString(FragementSearch.searchtype,”Advanced”);

        searchFragment.setArguments(args);

        fragmentmanager.beginTransaction().

        replace(R.id.content_frame, searchFragment).addToBackStack(null).commit();

        }
        mDrawerLayout.closeDrawer(mDrawerList);
        }

        This is on click code

        and Below is Back button click code

        @Override

        public void onBackPressed() {
        getSupportActionBar().setTitle(“Home”);

        super.onBackPressed();
        }

        Now I can move very well between 2 fragments

        but sir i have to maintain 4 levels.

        i mean from home i have to go keywordsearch fragment than from keywork search to searchresult fragment than detailsfragment so how to manage backtrack.

        on my keyword search fragment for moving from keywordsearch fragment to searchresult fagment i am using code place below

        FragmentManager fragmentmanager = getFragmentManager();

        fragmentmanager.popBackStack();

        FragmentSearchResult searchresultFragment = new FragmentSearchResult();

        Bundle args = new Bundle();

        args.putString(FragmentSearchResult.search_details,response);

        searchresultFragment.setArguments(args);

        fragmentmanager.beginTransaction().

        replace(R.id.content_frame, searchresultFragment).commit();

        Plz sir correct this code..Thank you for your reply sir…Thank you sir

  • TheMadBrewer

    Thank you very much, this helped me quite a bit.

    I made a few changes to suit my app that some may be interested in. In my case, I had “variable” NavDrawItems — depending on the settings and the device status some items would need to be hidden.

    I extended the NavDrawItem class by add a String tag.

    private String tag;

    and changed all the constructors (except the empty one) to pass this.

    Then when added NavDrawerItems to the drawer, I passed a tag that said which item it was.

    Then in the SlideMenuClickListener I got the NavDrawerItem that was selected and passed it to displayView, eg.

    NavDrawerItem ndi = (NavDrawerItem) parent.getAdapter().getItem(position);
    displayView(mdi, position);

    In displayView I replaced the switch block with a bunch of if-else if statements…

    String tag = ndi.getTag();

    Fragment fragment = null;

    if (tag.equals(TAG_HOME)) {

    ….

    } else if (tag.equals(TAG_SOMETHING_ELSE) {

    … etc.

    }

    Then to set the title, I just used the title from the passed NavDrawerItem object

    setTitle(ndi.getTitle());

    The position variable is used to set the selected drawer and one could do that by iterating thru looking for the tag but since the listener gives you that for free, I figured why not use it.

    Again, thanks and I hope this might help somebody else in the future.

  • Parth

    Hello, If i am in photos fragment class now i want to add another
    menumitems like “cupcake, php, orkut” etc. from fragment class (from photos fragment for ex.). its possible? and how to do?

  • JAYESH

    Hello…….Ravi ji…

    ANDROID HIVE is great source for android developer. And I learn android from ANDROID HIVE
    . thank u so much……..!!!!

  • saner akcali

    Hello Ravi,

    I am having some troubles with the code. I made some changes to your code and it works good on my Motorola Xoom 2 ( android 4.0.4) but I cannot get this code to work on phones such as Nexus5 (android 4.4.4) and GM discovery (android 4.2.1). The problem I get is null pointer exception on this line of code

    txtTitle.setText(navDrawerItems.get(position).getTitle());

    on the file named NavDrawerListAdapter.java

    Can you please help me through problem?

  • prasad Vdv

    Thanks for the example,

    I don’t want 22 and 50+ in slide menu. How to remove it?

    • Pragadees

      In MainActivity Java
      navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons.getResourceId(5, -1), true, “50+”));

      change to
      navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons.getResourceId(5, -1)));

  • Ravi

    hi..ravi Sir…I am getting one error and the code: getActionBar() is null every time and its a big issue I am facing…can you help me in solving out..thnx

  • Pravin Yadav

    I tried many examples on sliding menu but your’s is THE BEST
    Thank you

  • Hugo Martins

    Hi Ravi… Great tutorial.

    When testing I have a null pointer exception in the instruction
    “imgIcon.setImageResource(navDrawerItems.get(position).getIcon());” every time I change or start in landscape mode. IN portrait its perfect.

    Any idea?

  • Marcus Koh Chi Hao

    Can i ask how do i add a imageview to the sidebar to look something like Google I/O 2014 sidebar? i am unsure which lines to change inside the java file.

  • Lucas Teixeira

    Parabéns, muito bom o tutorial.

    • Elioenai Silva

      pq o meu ta dando erro na execução? sabe me dizer peguei o codigo e ja botei o v7.

  • Lucas Teixeira

    Sub-menu how to do? Example?

  • Hitesh Matnani

    hey @Ravi this was the awesome article. i need a help that is when we click on navigation slider icon it slightly goes in what i do to stop this i wanna it to be constant after click.

  • Ankit Aggarwal

    Hey ravi thanks for the great tuturial. this code worked fine for me. But in my app there are tabs with the action bar. I want the navigation drawer to draw over the tabs like in google music and some other google apps but it is not happening with your code. Any way to get that?

  • varun

    Hi ravi,I liked this tutorial and i have also tried out loved it,but i have one question how to add a listview inside this fragment since i am getting error like “Fragments cannot be cast into android.app.activity” can you please help me out ..Thank u

  • TheDemz
  • andrez123

    Do you have a example of slidemenu and tabhost in a Project?

  • sefa

    How can we open left menu when pressed hardware menu button?

  • Surjith Kumar J

    The click event of the drawer was not working when i add a togglebutton into it.

  • Nick

    How can I add a OnClickListener to a Fragment? If I use the listener in MainActivity I get a null exception, because the button is in a fragment. On the otherside i dont like to implement the database in every fragment. Maybe you have a solution for my Problem?

  • sefa

    mr. tamada i can’t add to actionbar anything. what is problem? why it is not working?

  • sefa

    Tamada you will answer ?

  • varun

    hi ravi how to add a listview inside fragment…plz will you ans my previous comments

  • Guest

    Hi Ravi,I’m trying to implement this tutorial in my app but I’m getting error on

    private void displayView(int position) {

    // update the main content by replacing fragments

    Fragment fragment = null;

    switch (position) {

    case 0:

    fragment = new HomeFragment(); Error is appearing here (incompatible types)

    break;

    I can’t control by using switch-case
    By the way I’m working on Android Studio

  • Hi Ravi,
    Thanks for sharing the tutorial.

    String fontPath = “fonts/RockFont.ttf”;
    Typeface tf = Typeface.createFromAsset(getAssets(), fontPath);
    TextView txtTitle = (TextView) convertView.findViewById(R.id.title);
    txtTitle.setTypeface(tf);

    I’ve tried adding the above code in the NavDrawerListAdapter.java file inorder to change the font but then the app crashes.

    Any help is appreciated.

    • Instead of

      Typeface tf = Typeface.createFromAsset(getAssets(), fontPath);

      Add

      Typeface tf = Typeface.createFromAsset(context.getAssets(), fontPath);

      Add the code in NavDrawerListAdapter.java now it’s working fine.

  • Hi all developers. i get an error cannot find method getFragmentmanager(); http://stackoverflow.com/questions/26395844/android-cannot-resolve-getfragmentmanager

  • mahadev dalvi

    hi Ravi ,

    thanks for that ..

  • chabii

    Hi, I’m afraid that android.support.v4.app.ActionBarDrawerToggle is now deprecated 🙁

    Could you indicate to us, how to fix this issue??

    thank you!

    • Aamir R

      use v7

  • Jaydeep

    HI ravi sir… This is nice tutorial .. i love it… I have only one question that i want to increase icon size of navigation actionbar so that which is near to title. How can i increase it fill parent.

  • Jaydeep

    How can i change the color of title and also background of actionbar

    • you_wanna_disqus?

      Use actionbarsherlock library to change the color of the actionbar.

      • Jaydeep

        Thanks.

  • BKS

    Hi, I want to change the navigation actionbar to right side…….Sliding also come to right side….pls
    help out

  • Nikhil

    Thank you vary much

  • Kelvin

    Hi Ravi Tamada,

    i would like to know how to put a title between fragments in the navigation drawer

  • Manny264

    How do you decrease the height of each navigation drawer list item? My attempts to simply change the height of the nav drawer item proved futile,ddnt work

    • If you observe navigation drawer adapter class, drawer_list_item.xml is inflated as navigation drawer item. So you have to adjust the height in drawer_list_item.xml file.

      • Lavish

        Hi Ravi,, I’m facing a problem.above example not working with samsung tab while it has kitkat version..can you please help me? getActionbar() return null always.

  • utsav

    Download’s not working

  • Zafer

    Hi Ravi,

    I’m using your implemantation in my app but I have a question on adding an item to sliding menu.For example I want to add different type of class such as Activity, FragmentActivity, Fragment together on sliding menu How can I implement of these different type of classes on sliding menu?

    • Ankur Agarwal

      Did you get anything?

  • cricket100

    Hi Ravi

    great tutorial.Since ActionBarDrawerToggle for v4 is deprecated, one has to use from v7. But the constructor for the same is different. It uses Toolbar as one of the parameteres. Could you plz let me know how to make the required changes ?

  • Innocent Udeogu

    This is the best resource on Navigation drawer online.

  • bagi

    when press back, how to back one fragment to another fragment? for example: from People fragment to Home fragment

  • satyamreddy

    In my eclipse i am using kitkat 4.4 emulator but i am getting below exception

    11-09 18:25:39.420: D/AndroidRuntime(1222): Shutting down VM
    11-09 18:25:39.420: W/dalvikvm(1222): threadid=1: thread exiting with uncaught exception (group=0xb2affd70)
    11-09 18:25:39.440: E/AndroidRuntime(1222): FATAL EXCEPTION: main
    11-09 18:25:39.440: E/AndroidRuntime(1222): Process: info.androidhive.slidingmenu, PID: 1222
    11-09 18:25:39.440: E/AndroidRuntime(1222): java.lang.RuntimeException: Unable to start activity ComponentInfo{info.androidhive.slidingmenu/info.androidhive.slidingmenu.MainActivity}: android.util.AndroidRuntimeException: You cannot combine swipe dismissal and the action bar.

  • Mahadev Dalvi

    hi..
    Ravi
    i want to show slider menu user wise means(out of five two menu show for end user and other fro admin please help me)

  • Jaydeep

    Hi ravi this all thing works for me. But i have one question that how can i support sliding menu drawer in verson like 2.2.3 or above. This is works on 4.0 + above. Please any idea.

    • if you want add sliding menu drawer in android api < 11, you must add Support Library in your project. You can search more about this on google. 😉

  • Gerard

    Hello. thanks for this tutorial. But how can I add or change the title/name of the menus in the nav drawer?

    • You can change or add in string.xml

      • t chọn home->ok
        people->ok
        photos->ok
        HOME->crash
        home include : form, maps, chỉ có layout
        m bit cách sửa chỉ với

  • Mahadev Dalvi

    i got solution thanks

  • JC

    android:listSelector=”@drawable/list_selector”
    android:background=”@color/list_background”/

    eclipse does not recognize this. Or do you want me to create my own because you did not wrote what you did here?

  • Bharath Nadig R

    Hi Ravi,

    Nice tutorial,it helps a lot for beginners …

    I have some doubts regarding Navigation Drawer.

    1.Can i use Activity instead of Fragments?

    2.Is it the right approach to use Activity instead of fragments?

    3.If it is the right approach,please provide me the small example,so that it helps a lot for beginners.

    I am not able to find a complete example of using activity instead of fragment

    Please ,i am waiting for your replay

    Again,Thanks a lot for your tutorial

  • Enamul

    Hi ravi,
    Thanks for the tutorial.It really helped me a lot.But I have an issue.I want to increase the touch margin so that the slide menu opens even when the finger is not drawn from the very left corner. I hope I will get a solution to this.please to do help me! Thanks in advance.

  • vishnu

    Thanks for this tutorial . I built my app and it looks awesome. I m very new to android programming and the way the codes are explained helped me to get it going. I had issues with the min sdk initially. I started with 8 to 21 . Got lot of errors. Then i changed to 14 to 21 and it worked . Please mention min and max sdk , it might be useful to someone like me .thanks again. i will follow this site for a very long time. All the best. 🙂

  • Karthik Kolanji

    Thank for this wonderful tutorial . I implemented this and is working fantastic. Now the problem is I need to implement Dual Navigational Drawer . When user clicks on items in LEFT drawer then its sub items should open in the Right drawer . How to achieve this using your existing
    code .. Pls help in this case

    • Ukor

      Let me know if you get an answer to this ….. we love to implement this too

  • Allan Dave

    Can you post the source code?. so that we will just import it..

    • Salim Alhassan

      The source code has already been posted. You can download it at the beginning of this article… 🙂

      • Allan Dave

        Yeah, sorry for that.. 🙂

  • Kumar

    how to add spalsh screen before starting this navigation drawer… please suggest me..

    • ukor

      There is tutorial on this site that handle that.

  • Razvi

    Is there a way to activate the menu from a specific button instead of the actionbar?

  • Víctor Herández

    Thanks for the tutorial, but what I can to reconcile app for android 2.x?

  • Sagar Devanga

    Getting this error

    Error:(97, 25) error: no suitable constructor found for ActionBarDrawerToggle(MainActivity,DrawerLayout,int,int,int)

    constructor ActionBarDrawerToggle.ActionBarDrawerToggle(Activity,DrawerLayout,Toolbar,int,int) is not applicable

    (argument mismatch; int cannot be converted to Toolbar)

    constructor ActionBarDrawerToggle.ActionBarDrawerToggle(Activity,Toolbar,DrawerLayout,T,int,int) is not applicable

    (cannot infer type-variable(s) T

    (actual and formal argument lists differ in length))

    where T is a type-variable:

    T extends Drawable,DrawerToggle declared in constructor ActionBarDrawerToggle(Activity,Toolbar,DrawerLayout,T,int,int)

    • Misaal Turakhia

      import android.support.v4.app.ActionBarDrawerToggle; //IMPORT THIS

      not
      import android.support.v7.app.ActionBarDrawerToggle;

    • you can down his demo and copy library in /libs/android-support-v4.jar..

  • Barış Çağan Kurtuluş

    How can I put list item like “Settings” align at the bottom of the list view? I google it a lot but I can not find the answer. The closest I get was http://stackoverflow.com/a/19254770, any help?

  • mahesh

    Hi,

    How can I update counter from child activity, I hope you understood this.
    For eg., in the above code, if want to Increase or decrease the count of “Communities” which is a separate function in a new activity.

    How can we achieve this? …

  • Sagar

    Thanks for this. Very helpful. I want a custom navigation drawer. and also set items in the drawer list dynamically, getting from json array. and also with header view. please help for this.

  • Andreas

    Hi. Great tutorial, but I do have one slight problem which makes the app unable to run:

    [2014-12-05 13:57:04 – FirstApp] C:Program Files (x86)DeveloperNy mappFirstAppresdrawablelist_item_bg_pressed.xml:3: error: Error: No resource found that matches the given name (at ‘endColor’ with value ‘@color/list_background_pressed’).

    I do not understand how I am supposed to solve this issue and any help would be much appreciated

    • Ukor

      open your color folder located in values (if you dont have one, create one) and add list_background_pressed

  • Albin

    Hello, very good tutorial, but I have encountered a slight issue. I’ve basicly copied most of your code and I have gotten one error. I do not understand what Im supposed to do and hope someone might give me an answer. In the MainActivity.java I copied your code at the bottom of the file and this have resulted in 2 “public class MainActivity” but the first one has “extends ActionBarActivity” and the second one which I copied from you has “extends Activtiy”

    The is the error:

    The type MainActivity is already defined MainActivity.java /FirstApp/src/com/example/firstapp line 51 Java Problem

    How can I solve this? I would be very happy if someone could help me

    • Ukor

      simply removed the one you copied that extend activity and leave yours which extends ActionBarActivity. This should work,

  • Ukor

    Thanks a lot.. please i will love to add title to my navigation drawer like the one on gmail and facebook, ho do i go about it?

    • sanjogstha

      Did you figure out the way ? @Ukor

  • arpit

    hi ravi how to add a listview inside fragment

    • chemegator

      Extend the fragment in question as listfragment. Then on mainactivity change that fragment that’s being chosen to listfragment and initialize it. Then on the xml of the fragment create a listview. be sure to import android.app.ListFragment. also create a new xml that’s going to be used in the list and add that to the adapter.

      private void displayView(int position) {

      // update the main content by replacing fragments

      Fragment fragment = null;

      ListFragment listfragment = null;

      switch (position) {

      case 0:

      fragment = new HomeFragment();

      break;

      case 1:

      listfragment = new FindPeopleFragment();

      break;

      case 2:

      fragment = new PhotosFragment();

      break;

      case 3:

      fragment = new CommunityFragment();

      break;

      case 4:

      fragment = new PagesFragment();

      break;

      case 5:

      fragment = new WhatsHotFragment();

      break;

      default:

      break;

      }

      if (fragment != null) {

      FragmentManager fragmentManager = getFragmentManager();

      fragmentManager.beginTransaction()

      .replace(R.id.frame_container, fragment).commit();

      // update selected item and title, then close the drawer

      mDrawerList.setItemChecked(position, true);

      mDrawerList.setSelection(position);

      setTitle(navMenuTitles[position]);

      mDrawerLayout.closeDrawer(mDrawerList);

      } else if (listfragment != null) {

      FragmentManager fragmentManager = getFragmentManager();

      fragmentManager.beginTransaction()

      .replace(R.id.frame_container, listfragment).commit();

      // error in creating fragment

      Log.e(“MainActivity”, “Error in creating fragment”);

      } else {

      }

      }

      XML file:

  • John David

    Hi ravi,
    Can u guide me how to have the drawer menu to right side of the screen
    what are the changes required to current tutorial?

    • 3mpty

      in main activity xml, change layout_gravity to end or right for list_slidermenu

      • John David

        System crashed when I changed in to
        android:layout_gravity=”end” (this is the only change i dd to the current code)

        • adnan

          i have this problem too.please help me.please

  • Kamal Katariya

    what is frame_container?? its not resolving. 🙁

  • Daniel

    Hi! Great tutorial. Just got one problem. When I try to substitute the icons with ones I have created for myself the app just keeps crashinh. And I have made sure my own icons got the right size, name and format.

  • Arijit

    hey….nice tutorial..thanks.. but i have a problem…every time i load any other fragment apart from the home fragment, and press the back key,the app closes.. i don want this to happen. i want to load the home fragment again on back key pressed from any other fragment… Hope you can help….thanks.

    • Sheychan

      create item drawbacks.. u save the last visited item number then if he press back button.. u do click that saved number

  • Sayaji

    how to add imageview and 2 textviews at the first menu listview item like header of listview. I want ot design navigation menus like facebook (First menu item). please help..

  • sviter

    In my mDrawerList is 8 and each fragment is on ListView. when you click on one of the ListView by onListItemclick opens another fragment. And when you open it , and then push again for the same fragment with a listview on mDrawerList, then flies exception. How to fix ?

  • andri kristiawan

    how to combine with web view after click on menu…

  • George

    how can I make the home button to show the actual title of the app ?

  • arpit

    hey..i want listview in the FindPeopleFragment.java page…..

  • George

    Can I use the same fragment method to implement another fragment within a fragment ???

  • Getting error the activity_main cannot be resolved ?

  • David Anderson

    I think the .xml files should be in layout folder instead, was it a mistake that you put in drawable folder?

  • Zakir

    I did the above steps, but the main content has a listView in a fragment (HomeFragment with List) and it does not capture any callbacks relating to Scoll or Touch. How can we achieve this? I want to have the main content with endless/infinite listView.

  • arpit

    how to put listview into the HomeFragment.java

    • sanjay thakur

      View rootView = inflater.inflate(R.layout.fragment_pages, container, false);

      ListView view= (ListView) rootView.findViewById(R.id.list_slidermenu);
      String[] AndroidOS = new String[] { “Cupcake”,”Donut”,”Eclair”,”Froyo”,”Gingerbread”,”Honeycomb”,”Ice Cream SandWich”,”Jelly Bean”,”KitKat” };
      ArrayAdapter adapter = new ArrayAdapter(getActivity(),
      android.R.layout.simple_list_item_1, AndroidOS);
      view.setAdapter(adapter);

      • @rpit Patel

        thanks

  • MD Danish Ansari

    can i make it from right to left

    • Armin

      hi
      just set android:layout_gravity=”end”, and it will come from right to left 🙂

  • david

    Hello Ravi thanks for the tutorial! I’ve been at this tutorial for a while, I finally got everything down, but when I get it over to my phone it crashes. I haven’t changed anything to the files you provided either, so I’m at a loss over what to do now.

  • Adarsha

    How can we add collapsible sub menu into the menu items ?

  • ehsan

    hi, thanks for nice tutorial. how to define listview in fragment activity?

  • hey when i select any item of list from nav drawer it just blink. for just a second.
    can you tell me why such thing happening ?

    • sanjay thakur

      please check your log cat …it will show you what error exactly are you facing …then catch the error

  • arpit

    .i can display data on activity using JSON..but i cant display it on sliding menu .
    fragment ..

  • jip098

    Nice tutorial! Thanks!

  • thanks for this tutorial.
    i really confused how to use fragment.
    i have app Activity with intent, Listview and other. how to make my activity become fragment class?..

    i really need help for this..

    • desnyki

      Here s a bit a of my source code of this list in a fragment you can use.

      public class DeviceListFragment extends Fragment {
      public List addressList = new ArrayList();
      public List deviceList = new ArrayList();
      private ListView listView;
      private DeviceListAdapter adapter;
      ProgressBar spinner;

      Fragment fragment = null;
      public DeviceListFragment(){}

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

      super.onCreateView(inflater,container,savedInstanceState);
      View rootView = inflater.inflate(R.layout.fragment_device_list, container, false);

      return rootView;
      }

      @Override
      public void onActivityCreated(Bundle savedInstanceState) {
      super.onActivityCreated(savedInstanceState);
      listView = (ListView) getView().findViewById(R.id.list);
      adapter = new DeviceListAdapter(this.getActivity(), deviceList);
      listView.setOnItemClickListener(new ListClickListener());
      spinner = (ProgressBar)getView().findViewById(R.id.progressBar1);
      listView.setAdapter(adapter);
      spinner.setVisibility(View.GONE);
      //thread it
      new MyAsyncTask().execute(deviceList);

      }
      }

  • LH

    I get a null pointer exception when I try to do getActionBar()

    Caused by: java.lang.NullPointerException: Attempt to invoke virtual method ‘void android.app.ActionBar.setDisplayHomeAsUpEnabled(boolean)’ on a null object reference

    In MainActivity.onCreate, after running setContentView(R.layout.activity_main), I should be able to call getActionBar(), but instead null is returned.

    Any ideas?

    • Jen

      I’m having the same issue 🙁

      • BlackWhite

        In your MainActivity:

        import android.support.v7.app.ActionBarActivity;
        import android.support.v7.app.ActionBarDrawerToggle;

        MainActivity extends with ActionBarActivity.

        replace all getActionBar() with getSupportActionBar()

        😉

        • Aurthohin Pavel

          I have extends MainActivity with ActionbarActivity.
          replace all getActionBar() with getSupportActionBar().
          and added

          import android.support.v7.app.ActionBarActivity;
          import android.support.v7.app.ActionBarDrawerToggle;

          still now i have java.lang.NullPointerException

  • voltan

    Hello
    How I can add sub menu by open / close icon ( like google inbox ) on this menu?

    Thanks

  • Jesse

    Hello, thanks for the tutorial. I added a webview to the home fragment bt when i opened the app on phne it forces close and crashes. I’ve used webview on an app with blank activity and it works fine, please is there a different way to add webview to fragments? Please help

  • Aurthohin Pavel

    When i run this project it crashed and in my Log cat it shows NullPoint Exception how i can solve it.
    This is my Log cat Error

    01-20 00:45:43.086: E/AndroidRuntime(19278): FATAL EXCEPTION: main
    01-20 00:45:43.086: E/AndroidRuntime(19278): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.sliding/com.example.sliding.MainActivity}: java.lang.NullPointerException

    01-20 00:45:43.086: E/AndroidRuntime(19278): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2355)

    01-20 00:45:43.086: E/AndroidRuntime(19278): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2391)

    01-20 00:45:43.086: E/AndroidRuntime(19278): at android.app.ActivityThread.access$600(ActivityThread.java:151)

    01-20 00:45:43.086: E/AndroidRuntime(19278): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1335)

    01-20 00:45:43.086: E/AndroidRuntime(19278): at android.os.Handler.dispatchMessage(Handler.java:99)

    01-20 00:45:43.086: E/AndroidRuntime(19278): at android.os.Looper.loop(Looper.java:155)

    01-20 00:45:43.086: E/AndroidRuntime(19278): at android.app.ActivityThread.main(ActivityThread.java:5511)

    01-20 00:45:43.086: E/AndroidRuntime(19278): at java.lang.reflect.Method.invokeNative(Native Method)

    01-20 00:45:43.086: E/AndroidRuntime(19278): at java.lang.reflect.Method.invoke(Method.java:511)

    01-20 00:45:43.086: E/AndroidRuntime(19278): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1029)

    01-20 00:45:43.086: E/AndroidRuntime(19278): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:796)

    01-20 00:45:43.086: E/AndroidRuntime(19278): at dalvik.system.NativeStart.main(Native Method)

    01-20 00:45:43.086: E/AndroidRuntime(19278): Caused by: java.lang.NullPointerException
    01-20 00:45:43.086: E/AndroidRuntime(19278): at com.example.sliding.MainActivity.onCreate(MainActivity.java:57)

    01-20 00:45:43.086: E/AndroidRuntime(19278): at android.app.Activity.performCreate(Activity.java:5066)

    01-20 00:45:43.086: E/AndroidRuntime(19278): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1101)

    01-20 00:45:43.086: E/AndroidRuntime(19278): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2311)

    • TRex

      What is your code block at line 57 in MainActivity.java?

      • Dekse

        mDrawerList.setOnItemClickListener(new SlideMenuClickListener()); ???

        • amy

          I have the same error of null pointer.
          can u share the solution how u rectified pls?

          • sanjay thakur

            your project can not find the same class of MainActivity plz check agin ..try out to check breakpoint from starting

  • Mateus Faria

    Hello, The download link is broken…. =`(…

  • Poggi Carlo

    complimenti x il tutorial
    vorrei poter rendere di colore divereso il menu quando e’ focusdable,
    come posso fare ? ho provato a cambiare il file list_selector

    android:state_focused = “true” />

    ma non funziona

  • neel

    this will Autometiclly handel back trace ????

  • Mr. Ed

    So how would you start a list to pagesfragment?

  • Abdullah

    How can use this code in terms of acitivity as this call fragments, how can i make this to work with intents. My MainActivity extends BaseActivity where i put the drawer codes
    But the app crashes. Plzzzz how can i not use fragments

  • Ilyes Atoui

    please how can i add sections separators to the listview in your code??

    • raamkum

      Hey! Did you add sections separators to the listview? I am also looking to implement the same? Thanks! If you have solved it can you post your liners here please?

      • Ilyes Atoui

        Sorry i saw your comment just now,, yes i fixed the problems ,,if you steel need a solution just contact me at my gmail spacelass@gmail.com

  • Sochinda

    Dear all,

    If I have more list item than show in the screen. when I set selected this listview always scroll position has changed and bring the selected item to the top, please let me know to keep scroll position?

    Thanks in advanced

  • Shruti

    Hi I am struggling to open up an activity inside the fragment, I wanted to use the “How to connect Android with PHP, MySQL” code with the code you have provided in this tutorial but as one uses fragments and the other doesnt it won’t let me add the feature to one of the fragments. Please can you advise on what would be the best way to use activities inside fragments.

    Any help would be appreciated!!

    • Santosh Sali

      mDrawerLayout.closeDrawer(mDrawerList);
      Intent intent = new Intent(NavigationDrawer.this,
      ShowPicActivity.class);
      startActivity(intent);
      return;

      use this code to open new activity

  • Naushad Anwar Siddiqi

    dear i want to use Web view that is for home, people i want to open website….i am new to android development could u tell me where should i post the code? with changes..

  • Patrick Melia

    Hi Ravi, can you do another example like this using the material design guidelines/recyclerview?

  • Stef

    Hello, I found your guides very useful. I’m developing an app and I used your sliding menu but I have one problem. I can’t make work the click listener for the slide menu list. I already have a click listener for my list view for the main page but even when I disable this listener the other one doesn’t work. Any ideas? I copied your code as it is here and i did changes only to match my data

  • hicham abdedaime

    Hi Ravi help me please hwo to add header in menu navigation with listview.addheader(); thanks

  • Salar Rastari

    Hi Ravi
    i get these errors:
    Error:(20, 26) No resource found that matches the given name (at ‘divider’ with value ‘@color/list_divider’).

    Error:(23, 29) No resource found that matches the given name (at ‘background’ with value ‘@color/list_background’).

    Error:(25, 28) No resource found that matches the given name (at ‘textColor’ with value ‘@color/list_item_title’).

    Error:(36, 28) No resource found that matches the given name (at ‘textColor’ with value ‘@color/counter_text_color’).

    Error:(6, 27) No resource found that matches the given name (at ‘color’ with value ‘@color/counter_text_bg’).

    Error:(5, 29) No resource found that matches the given name (at ‘startColor’ with value ‘@color/list_background’).

    Error:(6, 27) No resource found that matches the given name (at ‘endColor’ with value ‘@color/list_background’).

    Error:(5, 29) No resource found that matches the given name (at ‘startColor’ with value ‘@color/list_background_pressed’).

    Error:(6, 27) No resource found that matches the given name (at ‘endColor’ with value ‘@color/list_background_pressed’).

    • Salar Rastari

      hey guyz i forgot to create color.xml in values folder.
      THANK YOU SO MUCH RAVIIII 😀
      you are the best.

  • Santosh Sali

    thanks Ravi…….very nice discription very useful

    • You are welcome Santosh:)

      • Ah Ravi Can i expect Tabbed Activity for one of the Fragme

  • Wojtek Hołowiak

    Hey, I am stuck at adding new package. Recently I switched from Eclipse to Android Studio and I am a bit lost. How to add new package in Android Studio? Also, good tutorial 🙂

    • Junaid Ali

      In Android Studio,
      Inside folder, JAVA right click com.yourcompany.yourproject package -> New -> Package
      give a name to Package.

      To Add a Class,
      Right click recently create package -> New -> Java class

  • sndn

    How can you implement search in fragment?

  • John Murungwa

    HI, Thank you for the tutorial, I downloaded the code and tried to run it in Android Studio but it couldn’t run because it has not Gradle build. But that’s fine so i copied everything as I am trying to get a feel of how it works and see how to add that in my small project that i’m doing. But i’m getting error on: private void displayView(int position) {

    // update the main content by replacing fragments

    Fragment fragment = null;

    switch (position) {

    case 0:

    fragment = new HomeFragment();

    break;

    case 1:

    fragment = new FindPeopleFragment();

    break;

    case 2:

    fragment = new PhotosFragment();

    break;

    case 3:

    fragment = new CommunityFragment();

    break;

    case 4:

    fragment = new PagesFragment();

    break;

    case 5:

    fragment = new WhatsHotFragment();

    break;

    default:

    break;

    }

    It say,Incompatible type, Required: android.app.Fragment, Found: com.news24.IconFragment.HomeFragment.

    I am new to android developement and any help will be highly appreciated

    • sanjay thakur

      In your class HomeFragment declaration, do this:

      public class HomeFragment extends Fragment {
      ……

      And use import android.app.Fragment;

      not use import android.support.v4.app.Fragment;

  • youssef abaza

    How do I add a functional Search bar in the navigation drawer that filters the listview items?

  • samit Parade

    this is good site for new developers. But I had some issues with support libraries use.should i use V4 orV7 labraries. when i using same code with v7 libraries then action tab is not fiund?

    • sanjay thakur

      i thing u must use V4 libraries …bocz V7 is deprecated..and this project also use v4 check build.gradle ..

  • AndroidHive has always helped me in clearing my concepts about Android!! Thanks a TRILLION for writing a blog on Android and helping people !!

  • Sanjay Gupta

    This is very much useful tutorials.
    Thanks

  • Nick M

    This really is a great tutorial. It has served as a great building block. Any chance we can see a refresh for appcompat and toolbar?

  • Dieudonné Loïc

    This tutorial is really well explain and detailled, he helped me a lot. Thanks !!

  • Niklas Karlsson

    Whoho! Great guide! 🙂
    Btw: the red colour for mark in a list, can I change it?
    The what is hot icon, is this free to use?
    Now I “only” need to convert an activity to Fragments .. glurp

  • Bhavya

    Very useful tutorial. Thanks a lot. 🙂

  • Rohit Jadhav

    Thanks for uploading this stuff!

  • raamkum

    How to add Sections (Title) to the list? Say if I have 5 sections and items below it?

  • janarthanan

    How to change the font of action bar.

    • sanjay thakur

      getActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor(“#FFFA0073”)));

      this line of code will help you

  • Xpak

    hi , thx for this tutorial , it helps me a lot

    i have a problem , the slidemenu dont match with the phone full screen… any helps?

    sorry about my english and greeting from Chile!

    • sanjay thakur

      change width of activity_main.xml in listview

      like android:layout_width=”240dp” to android:layout_width=”fill_parent”
      hope so you want this

  • Jo

    The work is very nice by the Author. But this menu is not scrollable. So if you add more items to it, then you won’t see them.

    • Guest

      Mainly it is showing 6 options, and thereafter no options are displayed. From where we can remove the limitation? Plz help.

    • Jo

      see it is already there in code.

  • Shwet

    Hello… Nice… I have only One problem.. I placed one image button in one fragment layout..

    i want to use some task on (button.onclicklistener) event..
    so that i used getview().findbyviewid(r.id.imagebtn)…
    But i can not get onclicklistener method on that button object… please help me sir..

  • Gurneet Sodhi

    Hiee…Thanx for the tutorial..can u plz tell me how can i use activities instead of fragments…I have used Intent in switch case but the navigation drawer is not visible on all the other activities…really need help its for my college project.

  • alex

    Hello!

    nice tutorial i just have one problem:

    mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
    R.drawable.ic_drawer, //nav menu toggle icon
    R.string.app_name, // nav drawer open – description for accessibility
    R.string.app_name

    please help…

    • Neechi Raaj

      it seems v4 version is different from v7.
      In stackoverflow, they suggested to remove that parameter and it worked for me.

      mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
      R.string.app_name, // nav drawer open – description for accessibility
      R.string.app_name
      ) { …

      • can u add a link on stackoverflow for fixing this problem ?

        • sanjay thakur

          simple use V4 instead of V7

      • Mountain

        i have the same problem and i don’t fix it

  • Ulhas Patil

    Hey Ravi Please tell us how i draw my navigation drawer up-to status bar ?
    Can you do such tutorial for us..? It’s very rare tutorials on Google.

  • geethu

    Can u please share d android manifest file…….in d downloaded source code,its shown empty

  • Hi All. It;s with Urgent .I need a Tabbed Activity under any one of the Fragment.Could any body help me out?

    • sanjay thakur

      androidhive has a project demo with use of tabbed activity search it

  • Ashish Yashwant Mestry

    What should I do to dynamically get those icons from server instead of storing it locally? How could I do that?

    • Sherif Muhammad

      I think you get the item names from the http request and load the string array from them instead of the resources XML file ..

      • Ashish Yashwant Mestry

        I have done that already for the name, I am just asking about the icons.

        • You can get the icon url from the server by using google volley (networking library) and making a JSONObjectRequest and obtain the url in JSON. Later, use picasso library or the image loader in Volley itself to lazy load the images.

  • Heliex88

    Hi 🙂

    Thx, your tutorial is awesome !! Have a nice day 🙂

  • crime_master_gogo

    Thanks a lot .. this is very useful for beginners.

  • Ali Yavari

    How to set mDrawerToggle right to left?

    • sanjay thakur

      yes you can start drawer RIGHT_LEFT
      first to change gravity activtiy_main.xml gravity=”right ”
      the change little code onOptionsItemSelected i write below

      public boolean onOptionsItemSelected(MenuItem item) {
      if (item != null && item.getItemId() == android.R.id.home) {
      if (mDrawerLayout.isDrawerOpen(Gravity.RIGHT)) {
      mDrawerLayout.closeDrawer(Gravity.RIGHT);
      } else {
      mDrawerLayout.openDrawer(Gravity.RIGHT);
      }
      }
      return false;
      }

      • Ali Yavari

        but my Icon in action bar is left. how chane it?

  • Thanks for really helpful article, can you tell me please how can we associate/map ids with menus in drawer

    • Mountain

      Hi you. I’m doing on the map and have the same question

  • Hi!

    I started developer for Android and have questions about class “HomeFragment.java” and “fragment_home.xml” you can, please, show one example how add a new element on Screen?

    Thanks! …your example is the best!

    • Mountain

      you can download souce code and see it

  • Dare Olowoniyi

    Can any one tell me how i could be able to start PhotoFragment class from an Activity class?

    I was trying to start the class with an intent but it doesn’t seem to work

    Intent i = new Intent(getApplicationContext(), PhotoFragment.class);
    startActivity(i);
    finish();

    … This didn’t work when I tried it

    Can anyone pls tell me how i can go about starting this PhotoFragment class within an activity….

    • sanjay thakur

      you can not call intent from activity to fragment ..wrong way like on_button_click do that code if u add fragment

      PhotoFragment a=new PhotoFragment ();
      FragmentManager manager=getFragmentManager();

      FragmentTransaction transaction = manager.beginTransaction();
      // create any layout which is name is layout in your activity_main.xml

      transaction.add(R.id.layout, a, ” “);

      // transcation.commit is use to save the entire transaction
      transaction.commit();

      and PhotoFragment must be extends by Fragment and override onCreateView method

  • Peyman Ezzati

    Hi, this is LEFT_RIGHT sliding men. how can i make it RIGHT_LEFT?

    • sanjay thakur

      Hi..Peyman please have a look..
      yes you can start drawer RIGHT_LEFT
      first to change gravity activtiy_main.xml gravity=”right ”
      the change little code onOptionsItemSelected i write below

      public boolean onOptionsItemSelected(MenuItem item) {
      if (item != null && item.getItemId() == android.R.id.home) {
      if (mDrawerLayout.isDrawerOpen(Gravity.RIGHT)) {
      mDrawerLayout.closeDrawer(Gravity.RIGHT);
      } else {
      mDrawerLayout.openDrawer(Gravity.RIGHT);
      }
      }
      return false;
      }

      its working code i have also implements…

      • Peyman Ezzati

        thanks for answer.
        now drawer opens from RIGHT_LEFT. But the DrawToggle button is left side , how can i move it to right side? Abstractly how can i manage nav menu.

      • SourabhRustagi

        Nice !

  • Dheeraj Bansal

    Hi, I want to make slide menu item as expandable. like home item has some child and so on.

  • C:UsersShubhamworkspacePocketresdrawable-hdpilist_item_bg_pressed.xml:4: error: Error: No resource found that matches the given name (at ‘endColor’ with value ‘@color/list_background_pressed’). I think this is a problem with support library.

    This error is in my activity_main.xml file.

    • sanjay thakur

      have u create list_item_bg_normal.xml file in your drawable folder and also define list_background as color name in color.xml file under value folder

  • Ali Yavari

    Hi.how set onBackPressed for all Fragment going to homeFragmnet?

  • mohsen

    Hi!
    could anybody show me how to add tabs to one of these fragments?

  • Pedro Mazarini de Oliveira

    Hi, what part of this code is responsible for changing the main screen brightness for when u slide the menu on it?

    • sanjay thakur

      if (fragment != null) {

      FragmentManager fragmentManager = getFragmentManager();

      fragmentManager.beginTransaction()

      .replace(R.id.frame_container, fragment).commit();

      // update selected item and title, then close the drawer

      mDrawerList.setItemChecked(position, true);

      mDrawerList.setSelection(position);

      // setTitle()

      setTitle(navMenuTitles[position]);

      mDrawerLayout.closeDrawer(mDrawerList);

      } else {

      // error in creating fragment

      Log.e(“MainActivity”, “Error in creating fragment”);

      }

      this is code is actually modify all fragments

  • Nguyen

    Thanks a lot!….Could you please help me! How to I can change number in menu. Example I want to change 22 into other number of COMMUNITIES with not refresh sliding menu. Thanks for your help!

    • sanjay thakur

      basically this is hard code which is coming by this contractor….you can do hard code here

      public NavDrawerItem(String title, int icon, boolean isCounterVisible, String count){

      this.title = title;

      this.icon = icon;

      this.isCounterVisible = isCounterVisible;

      this.count = count;

      }

  • deepak

    This is the best example for navigation drawer only i want to know that how can i add ExpandableListView / Drill-Down in slide menu in this example ?

  • deepak

    how can i set different title for home / event etc ?

    • sanjay thakur

      title for home / event are just fragments.. so create fragment and give it name whatever you want ..

  • Youssef Hamane

    pliizz some one can help me to modifie in this sliding menu

    • Ilyes Atoui

      What you want exactly?

      • Youssef Hamane

        tnx friend exactly i want to do json parser in fragment to add and recieve data from mysql merci en avance.

        • Ilyes Atoui

          Salam alaikom,
          this my gmail dear Youssef spacelass@gmail.com
          contact me on my gmail and i will send you my code but just tell me what you really need

          • Youssef Hamane

            Ok i have send to u an email if u have time tnx by the way

          • Georgekutty George

            friend …i want also that code..plzzz..:)..i am working that project..
            georgekuttygeorge@gmail.com

  • naveen kumar Gupta

    i want source code like gmail like when user login then its shows email id and if user is not login then it show login/signup option

  • Hi, this is brilliant. For some reason, everything that reference R. is missing. What is that?!

    • kunal

      I am also having the same problem… whats the solution for this problem

      • I moved over to Android Studio and everything works 🙂

  • Davide Nova

    how can I add to the menu, the account zone with the user pic? (like all the other apps at the beginning of this article)?

  • Ali Yavari

    Hi. How to chnage text color in ActionBar?

  • Ashish Kumawat

    Iam getting java.lang.NullPointerException: Attempt to invoke virtual method ‘void android.app.ActionBar.setDisplayHomeAsUpEnabled(boolean)’ on a null object reference
    error please help me.

  • Ashish Kumawat

    Somebody reply

  • sanjay thakur
  • Naveed Bhati

    my app close without any error when i click up to 3 time on sliding menu can anyone help me thanks

    • codephillip

      Try checking your logcat

  • Muhammad Faisal

    Sir i want to open specific fragment of slider .e.g from calling specific fragment from other activity …In Mainactivity where i can edit the code to go specific fragment.

  • Indi Dwi

    I had problems with my application and I do not know why
    application that issued the message “Sorry, slidder menu has stopped”
    I use a studio android 1.2
    anyone can help my problem?
    Thank you …..

    • codephillip

      Try looking through your logcat. And also add logs to the code.

  • Dinesh Rijal

    hey help me plz!!
    i wan to add imageView scroll when opening the app,ie when clicking the Home”,
    then when clicking “Find people” wan to open another xml .. and when image ScrollView is click then also wan to show another Xml .plz give me idea how to impliment this
    Thankx in advance

  • ha ho

    how to make sub menu and header

  • andy

    could you please help me with your color.xml?

  • Hi can you please help me to add an activity in a fragment? For example I want to use setContentView but it is not working when extending Fragments class. I even tried using FragmentActivity but no use..

    • TheTruth

      You can’t add an Activity to a Fragment, it’s the other way round.setContentView is for Activities, the equivalent of setContentView in a Fragment is onCreateView

    • codephillip

      Just like he said, You cant add an activity to the fragment. But you can call the activity from the fragment:
      startActivity(getActivity(),ActivityTwo.class);

  • Red. Bk.

    Hello Ravi Tamada ! Thank you for this tutorial. However, I’m having some issues with the getActionBar().setDisplayHomeAsUpEnabled(true);

    it throws a Null Pointer Exception.

    Do you have an explanation ? Thanks !

    • Dan

      did you ever get the solution?

      • krishnakanth

        if u still facing problem, just change the Activity to Actionbar activity and getactionbar() to getSupportActionBar()

  • Hi, thanks for the tutorial, but I am unable to get the correct display. When I run the app, i get home button in the middle of the screen both horizontally and vertically and when i swipe open the menu, it is not showing any options. Here are the screenshot links – https://drive.google.com/file/d/0B1EgZKOsCGB3YjlfSHo2NzBkV1E/view?usp=sharing
    https://drive.google.com/file/d/0B1EgZKOsCGB3OHF0UUlsWGhwN2c/view?usp=sharing

  • Hi Ravi, this article is dated to 13th, Nov 2013. Is it still a latest tutorial to follow?

  • LINK BROKEN PLS Refresh-Reupload this project !

  • Biswajit Kumar Paul

    how the home fragment is shown when ever i open the app

  • Saurabh

    How can I download source code??

    • Just click on “Download Code ” button , Register Yourself and download the code.

  • Raghavendra

    In switch case there you have used constructor to call that class to return the layout, but i my case my class already extends activity here i cannot extends fragment , so tell me sir. what will i do now ?

  • hello
    how can i change the color of action bar ??

    • codephillip


      @color/orange
      @color/black

      add this code in the styles.xml in the position show above position
      @color/orange
      @color/black

      remember to make the color.xml file or hard code the colors

      • Yeah I know that color.xml
        and thnx dear

        • codephillip

          your welcome

  • i added imageviews in homefragment.xml but when i click thats imageview do nothing.i cant adding intent in homefragment.java.if i add its making FragmentActivity.and all code giving fail.
    Java is not accepting mutliple extend;like this ;
    public class HomeFragment extends Fragment,Activity implements View.OnClickListener {
    i can only write public class HomeFragment extends Fragment implements View.OnClickListener {

    • I am also facing same problem. could anyone tell us any solution ??

    • codephillip

      Java does not allow inheritance from many classes like C++, so inherit from one class

  • Arbeeorlar

    Pls i need tutorial for the middle image

  • codephillip

    Hey guys. I have 4 major activities, Is it possible to add activities to the navigation drawer instead of fragments.

  • Paras Sahu

    Hi Ravi,pls suggest me how to pass dynamic parameter in fragment

    fragment = new HomeFragment();
    break;

  • Sam003

    The Android Studio version of this great example: https://github.com/zz676/NavDrawer

  • waytoweb jain

    hey i want to use silding menu in my whole apps. how to use in smile activity with silding menu in action bar. means how to import that in our simple activity?

    • vinod

      boss I am also faced same problem. My Problem is how to add this slider menu to all activities. plz help me……

  • Arun Balaji

    thanxxx….

  • Bhavik Shah

    hello,

    The click event on the menu icon is not working?
    can anyone help me out what i am missing?

  • Mohamad

    hi thank
    I need to have the right menu؟

    Please advise in this case
    thanks

  • Shipra

    I have used the same code but it generates error of null pointer exception….how can i remove this??

  • kom

    i import this project lot of error in this project any body help me what is the problem?

    • Kuls

      what was the error you are facing ?

      • vinod

        boss I have a small doubt. My Problem is how to add this slider menu to all activities. plz help me……

  • Prashant Chaudhari

    hi, i am getting error on R.id.frame_container

  • MY OPINION

    I’ve got problem.I followed the steps I build it as apk and installed it on my phone, It says, ”Unfortunately, the *appname* has stopped.”

    What should I do? It’ll be a big help if someone answers my problem.

  • suram sridhar

    Hi Ravi, thanks for the code.

    Can you please clarify on the below question?

    In one of my fragment say CommunityFragment() – In this code I have one button called Update. On update CommunityFragement UI should get appended with the data. But here fragment page is not refreshing. Again I have to tap on the navigation drawer and choose Community page to see the updated changes.

    Can you please help me out on this?

  • Arpit

    Hello Guys

    Please Anyone help me with sliding drawer item in center How can i do that plsease help me thanks in advance.

  • Ashish Bhagat

    Hello Ravi, How can I move activity to right when sliding drawer opens?

    I tried by overriding OnDrawerSlide in Drawer listener but its not working.

    frame.setTranslationX(mDrawerList.getWidth() * slideOffset);

  • hamed

    how change slide menu right to left (from right side open & close too) ??plz help me

    • Try giving android:layout_gravity=”right” to ListView in DrawerLayout (check the 3rd point).

      • hamed

        Thank you..i change gravity of ListView from “start” to “right” and it open & close from right silde …ok but when i click on googlePlus icon, the app has crashed & closed! how fix it & change ActionBar to right to left too(Titles & icons of items & menu icon set in right side of ActionBar) ??
        tnx ravi

  • salman

    hi…what is difference beetwen state_activated & state_pressed ??
    i changed color of state_activated when it is true but there was no change in appearance…why !

  • Assylzhan Serikuly Zharzhanov

    Hi Ravi! Can I use some pieces of your code for my small project?(Of course free and no ads)

  • lok pun

    I am getting error within this code section help me :

    mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
    R.drawable.ic_drawer, //nav menu toggle icon
    R.string.app_name, // nav drawer open – description for accessibility
    R.string.app_name // nav drawer close – description for accessibility
    )

  • AG

    how can i change the home or other layouts and add a rss list view in home layout?

    • AG

      @ravi8x:disqus please answer me 🙂

  • bidhu

    hello ,I want to know how i can set a timer to switch on or off wifi data connection programmatically in android

  • Morteza

    hi
    i cant subscribe ,i try with gmail and yahoo but i did not get any email
    plz send me source code

  • Kuls

    Hola Buddy..!!
    This is one of the best tutorial site for Android Developer.
    I have refereed this code and i want to know how can i use custom font for this Navigation Text items with the use of setTypeface()..

    I am hoping positive response from your side regarding my issue.

    Happy Coding.. 🙂

  • TestName

    Please Help!

    I got these errors when i tried to start the app(After changing the MainActivity.java):

    08-19 16:04:57.755: E/AndroidRuntime(26898): FATAL EXCEPTION: main

    08-19 16:04:57.755: E/AndroidRuntime(26898): java.lang.RuntimeException: Unable to start activity ComponentInfo{ir.soltani.clashsave/PACKAGE_NAME.MainActivity}: java.lang.ArrayIndexOutOfBoundsException: length=5; index=5

    08-19 16:04:57.755: E/AndroidRuntime(26898): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2092)

    08-19 16:04:57.755: E/AndroidRuntime(26898): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2117)

    08-19 16:04:57.755: E/AndroidRuntime(26898): at android.app.ActivityThread.access$700(ActivityThread.java:134)

    08-19 16:04:57.755: E/AndroidRuntime(26898): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1218)

    08-19 16:04:57.755: E/AndroidRuntime(26898): at android.os.Handler.dispatchMessage(Handler.java:99)

    08-19 16:04:57.755: E/AndroidRuntime(26898): at android.os.Looper.loop(Looper.java:137)

    08-19 16:04:57.755: E/AndroidRuntime(26898): at android.app.ActivityThread.main(ActivityThread.java:4867)

    08-19 16:04:57.755: E/AndroidRuntime(26898): at java.lang.reflect.Method.invokeNative(Native Method)

    08-19 16:04:57.755: E/AndroidRuntime(26898): at java.lang.reflect.Method.invoke(Method.java:511)

    08-19 16:04:57.755: E/AndroidRuntime(26898): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1007)

    08-19 16:04:57.755: E/AndroidRuntime(26898): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:774)

    08-19 16:04:57.755: E/AndroidRuntime(26898): at dalvik.system.NativeStart.main(Native Method)

    08-19 16:04:57.755: E/AndroidRuntime(26898): Caused by: java.lang.ArrayIndexOutOfBoundsException: length=5; index=5

    08-19 16:04:57.755: E/AndroidRuntime(26898): at PACKAGE_NAME.MainActivity.onCreate(MainActivity.java:75)

    08-19 16:04:57.755: E/AndroidRuntime(26898): at android.app.Activity.performCreate(Activity.java:5047)

    08-19 16:04:57.755: E/AndroidRuntime(26898): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094)

    08-19 16:04:57.755: E/AndroidRuntime(26898): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2056)

    08-19 16:04:57.755: E/AndroidRuntime(26898): … 11 more

    • Åíshå Håméèð

      must be some value is less or more than ur array index,,, check ur arraylist

  • virat

    I am getting error within this code section help me :

    mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
    R.drawable.ic_drawer, //nav menu toggle icon
    R.string.app_name, // nav drawer open – description for accessibility
    R.string.app_name // nav drawer close – description for accessibility

    • Jose Stepherd Caster

      Import this : import android.support.v4.app.ActionBarDrawerToggle;

  • Morteza

    how i can use this in all activities of my app?

  • Michael

    How can I start an Activity from the Home Fragment?

  • vikash

    How to use FragmentActivity instead of Fragment ? I want to use FragmentActivity because im facing problem with Fragment. I want to use GoogleApiClient within FragmentActivity.

  • Prakash Kumar

    how can hide menu icon and tille text please help me of this code

  • Paras Shah

    i cant not download .. so can u help me or can u send on paras_shah12345@yahoo.co.in ?

  • 9i3

    Can you achvie the same result if you use fragment activity inside of fragments?

  • Abhinav Wagadre

    Hi ,I am abhinav. I had tweeted you regarding the same.
    I had created one login actvity using your tutorial. now i dont want register link on login page as login credentials will be provided by owner.
    now when a user is logged in he should see one acivity with hamburger menu.
    I tried implementing hamburger menu by your tutorial but it is for main activity.
    I want to know how to integrate these two screens/activities.
    first screen login.
    second screen : hamburger menu.

    no need of databse connectivity. need to build just the flow of app.

    kindly help, thanks in advance.

  • Debie Trihartono

    Hello I’m Debie.
    I’m trying to make a sliding menu without actionbar. so I dont use actionbar toogle
    I need a toogle button to open and close the sliding menu.
    Have you tried to make the same purpose button?

  • MAS

    How can I start an Activity from the Home Fragment?

    • Åíshå Håméèð

      put it to ur manifest file i.e place ur home fragment as launcher activity

      • Big Back

        can’t download, plz upload another host

  • Bitelchús

    Hi, I am trying to make a list of items in FindPeopleFragment() but when I put the onClick() method for the button the application explodes. I know it’s because the inflater but I don’t know how to solve it, because I need both layouts. Someone knows a solution for this?

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

    View rootView = inflater.inflate(R.layout.demos_activity, container, false);
    ListView myListView = (ListView) rootView.findViewById(R.id.listView);
    adapter=new ArrayAdapter(getActivity(), R.layout.demos_activity, R.id.textView, value);
    myListView.setAdapter(adapter);

    b = (Button) rootView.findViewById(R.id.button2);
    b.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
    ((Button)view).setBackgroundResource(R.drawable.ic_arrow2);
    }
    });
    return rootView;
    }

  • Kabia Cyprian

    hi very helpful tutorial. how can i use activities instead of fragments?

  • meysam

    i can not download

    help me !!

    • Åíshå Håméèð

      subscribe and then login, u would have download it

  • Amita Jain

    my slider is visible number of times.. i write same code

  • Alperen

    how can i add a header

  • Massire Dia

    .Thank you so much. Very helpful tutorial. Just follow step by step.
    It works for me 🙂

  • prince

    how to change the action bar title text color into white ? by default its black ?

    • indrajit narvekar

      Modify your theme.xml

      • Annesa

        I want do the same, change color of the action bar and the navigation icon. I don’t see theme.xml, any idea?

  • Mohit Khaitan

    I m not getting the list title in the toolbar, it is only showing the app title. I want to show the title of the current fragment that is clicked. Plz help !!

  • Russell Harrower

    What are you trying to get me to do in 9. I prefer to create a new package to keep all the model classes. So create a new package namedinfo.androidhive.slidingmenu.model

  • Åíshå Håméèð

    what to do if i want to make some of the listview item to be expandable ??? please answer me soon … its urgent

    • Åíshå Håméèð

      can u please make edition in the same code here

  • Karthi9474@gmail.com

    Hai ravi nice tutorial Thank you

    but i need some doubts i need to create tabhost in this fragment

    Example: now i create what is hot in fragment to create tabhost how to create whenever i create Main activity error

    break;

    case 4:

    fragment = new Fragment_Invoice_Details();

    break;

    case 5:

    fragment = new Account_Statement();

    break;

    case 6:

    fragment=new What is Hot();

    break;

    error occur in what is hot i cannot create in fragmentActivity how to create please help me

  • Chetan Tantod

    hello … I want to make app with search bar and sliding menu … I’m trying to mix codes of yours ofCostomizedListView and slidingMunuWithNavigationDrawer but not working ….. Please HElp ..

  • Nitish Lad

    help…getting exception in ”

    getActionBar().setDisplayHomeAsUpEnabled(true);

    Caused by: java.lang.NullPointerException: Attempt to invoke virtual method ‘void android.app.ActionBar.setDisplayHomeAsUpEnabled(boolean)’ on a null object reference
    at com.fifthdimensiontech.slidemenu.MainActivity.onCreate(MainActivity.java:86)

    • Nikhil Gaur

      I am also getting same error. Please let me know if you got the solution.

      Ravi please let us know the solution if you have any. Stuck at this error for more than last 8 hours. 🙁

    • Kal-El Carvalho

      I am also getting same error too!

    • divya

      replace with this piece of code, getSupportActionBar().setDisplayHomeAsUpEnabled(true);

      • safvan.p

        This code is used in Android studio because it is advanced

  • Shama Agrawal

    Hey guys,I am able to design navigation drawer but its opening on Sliding,I want it to open using that “navigation Icon” ,how to do that?

    • Sachin Rajput

      hello baby , what is the prblm cming tell me i have done this

    • safvan.p

      you mean <– one want set manually

  • Junie Negentien (Juice Meal Ki

    thanks for the teachings. im a new beginner in android programming i learn so much about this tutorial. again thank you.

  • Venktesh Sakthi

    here color.xml file is missing

  • Big Back

    send me code plz, i can’t download code

  • Roshana

    Best tutes ever…. Tnks a lot..

  • LOL

    hi sir, how can i disable the sliding menu for my login page

  • Amitay Molko

    download is broken 🙁

    • Paul Nye

      I’m sorry to interrupt, but I’m new to StackSkills/StackSocial and I have no idea how to start the course I signed up for. When I click Start in the course curriculum section I’m simply taken to a page of comments. These comments also are asking how to actually start the course. Am I doing something wrong or is thi just a scam by Eduonix? I purchased a 10 unit development bundle called Javascript Development Bundle. Any experience that might help me?

      Thanks – Paul
      Pay What You Want: Javascript Development Bundle

      that includes
      Projects in ExpressJS – Learn ExpressJs building 10 projects
      Eduonix Learning Solutions
      0%
      COMPLETE
      Projects In JavaScript & JQuery

      Eduonix Learning Solutions
      0%
      COMPLETE
      Learn NodeJS by Building 10 Projects

      Eduonix Learning Solutions
      0%
      COMPLETE
      Learn MeteorJS By Building 10 Real World Projects

      Eduonix Learning Solutions
      0%
      COMPLETE
      Learn JavaScript Server Technologies From Scratch

      Eduonix Learning Solutions
      0%
      COMPLETE
      Learn Apache Cassandra from Scratch

      Eduonix Learning Solutions
      0%
      COMPLETE
      3D Programming with WebGL and Babylon.js for Beginners

      Pablo Farías Navarro
      0%
      COMPLETE
      Rapid D3 JS

      Packt Publishing
      0%
      COMPLETE
      Mastering D3

      Packt Publishing
      0%
      COMPLETE
      Learn NoSQL Database Design From Scratch

      Eduonix Learning Solutions
      0%
      COMPLETE
      Projects in AngularJS – Learn by Building 10 Projects

      Eduonix Learning Solutions
      0%
      COMPLETE
      Learn NoSQL Database Design With CouchDB

  • Iman

    Hi . . . Tnx for your help
    I have a problem with Action Bar . . .
    I get This Error . . . java.lang.nullpointException . . . how Handle it ?????

  • akhilesh

    Hi thnx for your help..
    I have a doubt.. is it possible to show navigation drawer on top of custom action bar??

  • Paresh Gupta

    i can’t download send link in my mail id g.paresh123@gmail.com

    • safvan.p

      esly log with facebook

  • Anon

    I have an error saying- ‘cannot resolve method displayView(0)’! Can anyone help please?

    • safvan.p

      private void displayView(int position) {
      // update the main content by replacing fragments
      }
      in MainActivity

  • Ashu Kumar

    not able to download project, and also no link generated while subscribe

  • Ashana. Jackol

    java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child’s parent first.

    using android studio….

  • Akshay Patil

    To those getting a null pointer exception….

    Extend your MainActivity class with AppCompatActivity.

    Then replace :

    getActionBar().setDisplayHomeAsUpEnabled(true);
    getActionBar().setHomeButtonEnabled(true);

    With:

    assert getSupportActionBar() != null;
    getSupportActionBar().setDisplayShowHomeEnabled(true);
    getSupportActionBar().setHomeButtonEnabled(true);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    And further replace getActionBar() in setTitle(), onDrawerOpened() & onDrawerClosed() with getSupportActionBar()

  • Aslam Patel

    how to user this menu in multipal activity i try but not working..

    • vinod

      hi boss. I am also faced same problem. are you got the solution!!!!!!!!!

      • Aslam Patel

        yes i can solve this problem

        • vinod

          plz, help me boss. how can apply this slide menu to all activities.

        • vinod

          plz explain me…sir

  • Akshay kumar

    Hello Sir, i used your code but now i have set drawer item dynamically with the value coming from Sqlite database. I have Created my db and it is returning me List, exmaple List. This i have to set on drawer items. Help me

    • jerofad

      Though I am new to Android, I stumbled on something like that and I discovered that instead of using ArrayAdapter, use CursorAdapter. So just try and check it out and I hope it works

  • Praveen Kumar

    Sir, I wanted to know how will we open other fragment using a button present on any of the fragments.

  • Niranjan

    Good tutorial! Very helpful 🙂 Thanks

  • Chaitanya Baweja

    Hi. Pls help me out..

    I’m getting a run time exception

    01-10 11:00:18.518: E/AndroidRuntime(14386): Caused by: java.lang.NullPointerException: Attempt to invoke virtual method ‘void android.widget.ListView.setOnItemClickListener(android.widget.AdapterView$OnItemClickListener)’ on a null object reference

    Here is the code

    mDrawerList.setOnItemClickListener(new SlideMenuClickListener());

  • AShu

    thanks for great tutorial
    however can u please explain how to add slider menu icons (navDrawerItems icon) Dynamically using bitmap , as in your code u used typed array to add icons to get icons values from string.xml file is there any way to add icons from bitmap , into slider menu or hwo to add new value into typedarray item Dynamically ? if yes, comment, wating for reply

    thanks

  • shafaque

    Sir how to add search on the top of this navigation drawer?

  • Venktesh Sakthi

    how to add sub-categories in navigation drawer?

  • Johnny TwoShoes

    your download link doesn’t work

  • |/|@¥@|||€

    Hello sir, thanks for giving nice tutorial. Can you please tell me how to add header like gmail and expandable list inside the navigation items??

  • indrajit narvekar

    Thanks Great Tutorial….

    How could I change static navigation arrow in animation 2 3 lines

  • Angga Zan

    hi…thanks for great tutorial…this is work well for me…

    i have some question, but first i’m sorry for my bad english hope you can understand what i mean :
    1. how to automaticaly refresh counter number from server using json when i open navigation drawer?for example get count of realtime current new what’s hot item…

    2. in my app, user must login first before they can enter MainActivity that contain this Navigation Drawer and use sharedpreference to save logged in user data, how i can get sharedpreference on fragment to get logged in user data like userid, name, etc?

    3. how to sent extra variable like userid when i click menu on navigation drawer?for example when i click Photo from navigation drawer i want to sent userid to photofragment, so it will only display photo(s) of logged in user

    4. on my old app, i use dashboard layout menu and use intent to redirect what user click menu on that dashboard to destination activity class, but now i want to change that old dashboard layout menu to navigation drawer menu, can i use current activity class as fragment?

    Sorry if i ask too much question because i’m very very beginer in android application development…i hope anyone can help to answer my question…thanks before…

  • Rohit

    Hi thanks for this amazing tutorial as i am new to android although i gone through your tutorial and implemented this project. But, i need your help i want to reduce the height between the two item within the menu and also i want to to sub menu for the menu can you guide me how to achieve this.

  • Hardik Verma

    In onCreateOptionsMenu I am getting an error on menu in R.menu.main
    It says menu cannot be resolved

    • Ashish Mathur

      create a menu resource file in menu folder under res folder

  • vinod

    can we write strings home,find people, photos , communites in telugu language. plz help me….

    • Nikola Brodar

      yes, you can do this. Just explore little bit code, and you will see it, it is not so hard.
      sorry I’m little bit lazy for searching something like this.

      • vinod

        yes, I got that solution. but it visible good in android genymotion emulator. but, didn’t get correct output in default emulator in android eclipse. plz help me….

  • Shoaib Farhan

    If You are getting Null pointer Exception at this line
    getSupportActionBar().setDisplayHomeAsUpEnabled(true); in android studio,
    u have to change MainActivity extends AppCompatActivity and
    u have to replace getActionBar() to getSupportActionBar()
    Finally its excute

    • Amr Elbrolosy

      i replaced both of them but the same error what can i do ?

  • night,

    thanks for the tutorial. please advice and criticism on my first application

    https://drive.google.com/file/d/0B3eiYbiyWsShbEg4SWRxMzdnU2s/view?usp=sharing

    thank you

  • Kiran Kumar S

    Hello Ravi, that was a nice tutorial, I have a slight different requirement i.e I need to have same navigation drawer shared among different activities instead of fragments. can you suggest me how to achieve this. My app is already built and have different activities, but now we decided to change out layout to navigation drawer.

    • Nikhil Kumar Reddy

      kiran i am also facing the same issue if you find any solution kindly inform me……..thanks in advance.

      • Kiran Kumar S

        Hello Nikhil, We decided to hold from migrating to navigation drawer for now. will let you know, when I accomplish that. Thanks.

  • Ivan Cyrillus

    how to change the color of slide menu? Tq

  • Sma Rahman

    Hi…First I would like to thank you for a nice tutorial.This is worked for me, But I faced a problem like when I click back button it came out the application. But in my application I need to go previous fragment when I click back button. I am using your code, if it is possible in your code, please give me a solution.

  • Vikas Gupta

    Hello Sir, I somehow managed to make this code working but i want this navigation drawer to take all the height and it should come above the action bar like the navigation drawer of medium app.
    How can i do that.

  • Pruthvi Reddy

    Hi.sir..This tutorial worked for me..thanks a lot..but my problem is when i click back button its coming out of the application..but i want when click back button it should go previous fragment..please help me.and i Implemented fragment replacement in your code..but when replace happen..it displaying previous fragment name in action bar..can you help me..

    • Can u tell me what we have to used as R.menu.main.It is not provided in the code.

  • Dolly kumbhalkar

    Hello Sir, I create the navigation drawer from this code but my app is unfortunately stop.. can you help me..

  • Hey!! I think you missed to add color file in the code above

  • sagar

    where do i use all that floatingactionbutton , toolbar and all other things. this drawer layout only have its own layout. i want drawer layout and all other things. then another content_main.xml which contain the main part. this is how new version of android layouts are defined in android studio. please do suggest.

  • Avitu

    Hello Sir, I tried this tutorial but when i run my app is unfortunately stop.. What should i do?

  • prince singla

    Hello Sir, I tried this tutorial but when i run my app is unfortunately stop.. What should i do?

    • Sergii Putintsev

      Try to use standard app in android studio, it will work perfect with AppCompatActivity
      the approach in the example is very old

      • ნიკა ხარაძე

        I have same problem , anyone can suggest us how to make this code work ? i guess some other library mast import but i have no idea which one .

  • MrX

    hello, thanks for a good tutorial, but i have some question, in slidder menu, there are number 22 and 50 in comunities and whts hot, where is the code location? thanks for any answer 🙂

    • Adrian Buciuman

      the code is located in MainActivity, when you add navDrawerItems

      navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons.getResourceId(3, -1), true, “22”));

      // Pages

      navDrawerItems.add(new NavDrawerItem(navMenuTitles[4], navMenuIcons.getResourceId(4, -1)));

      // What’s hot, We will add a counter here

      navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons.getResourceId(5, -1), true, “50+”));

  • Ricky Wijaya

    hello sir, thank for a good tutorial, but i have a request.. can u make tutorial to combine sliding menu and tabsswipegesture sir? thank anyway..

  • Shailesh Limbadiya

    Hello Ravi bhai this tutorial is very helpful for me for understanding to how sliding menu work. But now i want to same thing in material design i try too much but i don’t know how to design same sliding menu in material design, i use your Material design demo but i don’t know how to set image and counter in particular row if possible then please help me… 🙂

  • vinod

    ravi sir, how can we add this slide menu to multiple activities. can we add a activities in the place of fragments!!!!!!!!!

  • Swãrâñ Gõdlã

    I’m not able to download the code

  • Kurtca Kaplan

    I got like that errors How can i fix can you help me? I tried lots of things but it doesnt work.

    Error:(89, 20) error: no suitable method found for setAdapter(NavigationDrawerAdapter)

    method ListView.setAdapter(ListAdapter) is not applicable

    (actual argument NavigationDrawerAdapter cannot be converted to ListAdapter by method invocation conversion)

    method AbsListView.setAdapter(ListAdapter) is not applicable

    (actual argument NavigationDrawerAdapter cannot be converted to ListAdapter by method invocation conversion)

    method AdapterView.setAdapter(ListAdapter) is not applicable

    (actual argument NavigationDrawerAdapter cannot be converted to ListAdapter by method invocation conversion)

    —-AND—-

    Error:(175, 28) error: incompatible types

    required: Fragment

    found: GuidesFragment

  • Kurtca Kaplan

    What is the solution please help me? I’m trying for 3 days but i didnt solve!
    Error:(90, 32) error: constructor NavigationDrawerAdapter in class NavigationDrawerAdapter cannot be applied to given types;

    required: Context,List

    found: MainActivity,int

    reason: actual argument int cannot be converted to List by method invocation conversion

  • Bella Ayudita

    how to change drawer (icon and listview) direction to right?

  • Mani

    when i download then import and run this project it works fine. but when i write this code in Android Studio 2.1 then error comes why so

    • Huyền Nguyễn

      me too

  • Patidar JV

    hello sir
    my error plz ans….
    06-06 15:00:19.984 14586-14586/com.s_demo E/AndroidRuntime: FATAL EXCEPTION: main

    Process: com.s_demo, PID: 14586

    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.s_demo/com.s_demo.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method ‘void android.app.ActionBar.setDisplayHomeAsUpEnabled(boolean)’ on a null object reference

    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)

    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)

    at android.app.ActivityThread.-wrap11(ActivityThread.java)

    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)

    at android.os.Handler.dispatchMessage(Handler.java:102)

    at android.os.Looper.loop(Looper.java:148)

    at android.app.ActivityThread.main(ActivityThread.java:5417)

    at java.lang.reflect.Method.invoke(Native Method)

    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)

    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

    Caused by: java.lang.NullPointerException: Attempt to invoke virtual method ‘void android.app.ActionBar.setDisplayHomeAsUpEnabled(boolean)’ on a null object reference

    at com.s_demo.MainActivity.onCreate(MainActivity.java:88)

    at android.app.Activity.performCreate(Activity.java:6237)

    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)

    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)

    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)

    at android.app.ActivityThread.-wrap11(ActivityThread.java)

    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)

    at android.os.Handler.dispatchMessage(Handler.java:102)

    at android.os.Looper.loop(Looper.java:148)

    at android.app.ActivityThread.main(ActivityThread.java:5417)

    at java.lang.reflect.Method.invoke(Native Method)

    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)

    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

  • Rachana

    Hello
    Thank you for the code it worked perfectly,but i want to implement image gallery in photos widget i tried all the ways but its not taking,please guide me to implement a gallery widget in the same sliding menu.

  • vinod

    ravi sir, I have developed side bar with multiple activities. but it works fine in 5th, 6th versions. but it crashes in 4th versions. plz help me sir…

    • Check the LogCat

      • vinod
      • vinod

        06-08 11:25:59.114: I/dalvikvm(4347): Could not find method android.app.ActionBar.setHomeAsUpIndicator, referenced from method com.example.sidebaractivity.SidebarBaseActivity.onCreate

        06-08 11:25:59.114: W/dalvikvm(4347): VFY: unable to resolve virtual method 8: Landroid/app/ActionBar;.setHomeAsUpIndicator (I)V

        06-08 11:25:59.114: D/dalvikvm(4347): VFY: replacing opcode 0x6e at 0x00ca

        06-08 11:25:59.130: D/dalvikvm(4347): GC_FOR_ALLOC freed 88K, 8% free 2620K/2824K, paused 3ms, total 4ms

        06-08 11:25:59.130: I/dalvikvm-heap(4347): Grow heap (frag case) to 3.742MB for 1127532-byte allocation

        06-08 11:25:59.134: D/dalvikvm(4347): GC_FOR_ALLOC freed 2K, 6% free 3718K/3928K, paused 3ms, total 3ms

        06-08 11:25:59.138: D/dalvikvm(4347): GC_CONCURRENT freed <1K, 6% free 3718K/3928K, paused 0ms+0ms, total 2ms

        06-08 11:25:59.142: D/AndroidRuntime(4347): Shutting down VM

        06-08 11:25:59.142: W/dalvikvm(4347): threadid=1: thread exiting with uncaught exception (group=0xa6167908)

        06-08 11:25:59.142: E/AndroidRuntime(4347): FATAL EXCEPTION: main

        06-08 11:25:59.142: E/AndroidRuntime(4347): java.lang.NoSuchMethodError: android.app.ActionBar.setHomeAsUpIndicator

        06-08 11:25:59.142: E/AndroidRuntime(4347): at com.example.sidebaractivity.SidebarBaseActivity.onCreate(SidebarBaseActivity.java:96)

        06-08 11:25:59.142: E/AndroidRuntime(4347): at com.example.sidebaractivity.MainActivity.onCreate(MainActivity.java:17)

        06-08 11:25:59.142: E/AndroidRuntime(4347): at android.app.Activity.performCreate(Activity.java:5104)

        06-08 11:25:59.142: E/AndroidRuntime(4347): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)

        06-08 11:25:59.142: E/AndroidRuntime(4347): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)

        06-08 11:25:59.142: E/AndroidRuntime(4347): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)

        06-08 11:25:59.142: E/AndroidRuntime(4347): at android.app.ActivityThread.access$600(ActivityThread.java:141)

        06-08 11:25:59.142: E/AndroidRuntime(4347): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)

        06-08 11:25:59.142: E/AndroidRuntime(4347): at android.os.Handler.dispatchMessage(Handler.java:99)

        06-08 11:25:59.142: E/AndroidRuntime(4347): at android.os.Looper.loop(Looper.java:137)

        06-08 11:25:59.142: E/AndroidRuntime(4347): at android.app.ActivityThread.main(ActivityThread.java:5041)

        06-08 11:25:59.142: E/AndroidRuntime(4347): at java.lang.reflect.Method.invokeNative(Native Method)

        06-08 11:25:59.142: E/AndroidRuntime(4347): at java.lang.reflect.Method.invoke(Method.java:511)

        06-08 11:25:59.142: E/AndroidRuntime(4347): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)

        06-08 11:25:59.142: E/AndroidRuntime(4347): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)

        06-08 11:25:59.142: E/AndroidRuntime(4347): at dalvik.system.NativeStart.main(Native Method)

        06-08 12:06:08.490: W/dalvikvm(4593): threadid=1: thread exiting with uncaught exception (group=0xa6167908)

        06-08 12:06:08.490: E/AndroidRuntime(4593): FATAL EXCEPTION: main

        06-08 12:06:08.490: E/AndroidRuntime(4593): java.lang.NoSuchMethodError: android.app.ActionBar.setHomeAsUpIndicator

        06-08 12:06:08.490: E/AndroidRuntime(4593): at com.example.sidebaractivity.SidebarBaseActivity.onCreate(SidebarBaseActivity.java:96)

        06-08 12:06:08.490: E/AndroidRuntime(4593): at com.example.sidebaractivity.MainActivity.onCreate(MainActivity.java:17)

        06-08 12:06:08.490: E/AndroidRuntime(4593): at android.app.Activity.performCreate(Activity.java:5104)

        06-08 12:06:08.490: E/AndroidRuntime(4593): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)

        06-08 12:06:08.490: E/AndroidRuntime(4593): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)

        06-08 12:06:08.490: E/AndroidRuntime(4593): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)

        06-08 12:06:08.490: E/AndroidRuntime(4593): at android.app.ActivityThread.access$600(ActivityThread.java:141)

        06-08 12:06:08.490: E/AndroidRuntime(4593): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)

        06-08 12:06:08.490: E/AndroidRuntime(4593): at android.os.Handler.dispatchMessage(Handler.java:99)

        06-08 12:06:08.490: E/AndroidRuntime(4593): at android.os.Looper.loop(Looper.java:137)

        06-08 12:06:08.490: E/AndroidRuntime(4593): at android.app.ActivityThread.main(ActivityThread.java:5041)

        06-08 12:06:08.490: E/AndroidRuntime(4593): at java.lang.reflect.Method.invokeNative(Native Method)

        06-08 12:06:08.490: E/AndroidRuntime(4593): at java.lang.reflect.Method.invoke(Method.java:511)

        06-08 12:06:08.490: E/AndroidRuntime(4593): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)

        06-08 12:06:08.490: E/AndroidRuntime(4593): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)

        06-08 12:06:08.490: E/AndroidRuntime(4593): at dalvik.system.NativeStart.main(Native Method)

        06-08 12:11:08.918: I/Process(4593): Sending signal. PID: 4593 SIG: 9

  • suraj kumar

    Sir i need an perfect code of location based services so please help me

  • Lalu Septiawan Dan Ibu

    Sir, from this apk code i want to add the menu like this, if i click Find People menu on apk then apk bring me to page listview menu, in apk just bring me to page just logo find people but i want to change that page find people logo with listview, how to do it. thanks

  • Bobie Chaniago

    why i can’t download it sir..?

  • Manish Kumar

    Getting this error

    06-26 20:02:47.071 10829-10829/tiphinbox.mainapp E/AndroidRuntime: FATAL EXCEPTION: main

    Process: tiphinbox.mainapp, PID: 10829

    java.lang.RuntimeException: Unable to start activity ComponentInfo{tiphinbox.mainapp/tiphinbox.mainapp.ContActivity}: java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.

    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)

    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)

    at android.app.ActivityThread.-wrap11(ActivityThread.java)

    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)

    at android.os.Handler.dispatchMessage(Handler.java:102)

    at android.os.Looper.loop(Looper.java:148)

    at android.app.ActivityThread.main(ActivityThread.java:5417)

    at java.lang.reflect.Method.invoke(Native Method)

    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)

    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

    Caused by: java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.

    at android.support.v7.app.AppCompatDelegateImplV7.createSubDecor(AppCompatDelegateImplV7.java:343)

    at android.support.v7.app.AppCompatDelegateImplV7.ensureSubDecor(AppCompatDelegateImplV7.java:312)

    at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:277)

    at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)

    at tiphinbox.mainapp.ContActivity.onCreate(ContActivity.java:45)

    at android.app.Activity.performCreate(Activity.java:6237)

    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)

    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)

    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)

    at android.app.ActivityThread.-wrap11(ActivityThread.java)

    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)

    at android.os.Handler.dispatchMessage(Handler.java:102)

    at android.os.Looper.loop(Looper.java:148)

    at android.app.ActivityThread.main(ActivityThread.java:5417)

    at java.lang.reflect.Method.invoke(Native Method)

    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)

    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

  • Avikal Prakash

    Please sir help me,
    Getting the error
    07-08 10:49:05.061 2151-2151/com.example.slidemenu1 I/art: Not late-enabling -Xcheck:jni (already on)
    07-08 10:49:05.061 2151-2151/com.example.slidemenu1 I/art: Late-enabling JIT
    07-08 10:49:05.066 2151-2151/com.example.slidemenu1 I/art: JIT created with code_cache_capacity=2MB compile_threshold=1000
    07-08 10:49:05.185 2151-2151/com.example.slidemenu1 W/System: ClassLoader referenced unknown path: /data/app/com.example.slidemenu1-2/lib/x86
    07-08 10:49:07.055 2151-2151/com.example.slidemenu1 D/AndroidRuntime: Shutting down VM
    07-08 10:49:07.102 2151-2158/com.example.slidemenu1 W/art: Suspending all threads took: 23.823ms
    07-08 10:49:07.102 2151-2151/com.example.slidemenu1 E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.slidemenu1, PID: 2151
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.slidemenu1/com.example.slidemenu1.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method ‘void android.app.ActionBar.setDisplayHomeAsUpEnabled(boolean)’ on a null object reference
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
    at android.app.ActivityThread.-wrap11(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5417)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
    Caused by: java.lang.NullPointerException: Attempt to invoke virtual method ‘void android.app.ActionBar.setDisplayHomeAsUpEnabled(boolean)’ on a null object reference
    at com.example.slidemenu1.MainActivity.onCreate(MainActivity.java:87)
    at android.app.Activity.performCreate(Activity.java:6237)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
    at android.app.ActivityThread.-wrap11(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5417)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
    07-08 10:49:09.617 2151-2158/com.example.slidemenu1 W/art: Suspending all threads took: 38.311ms

  • Thiyakarajan

    hi sir,how to create the slide menu title and profile?

  • lakshman

    Hi sir thanks for the code its working fine, but I want to add a image in drawer menu how can i add it.

  • duc phungvan

    great job sir!

  • Jhon Ishmael Montenegro

    Hi Ravi, I just want to ask you a question. I am planning to create a custom launcher app that displays the all widgets installed in app to fragment/view pager. Do you think it is possible? Am I able to implement the widgets in my activity? Hope to you from you soonest! Thanks in advance.

  • Manish Kumar

    android.view.InflateException: Binary XML file line #26: Binary XML file line #26: Error inflating class android.support.design.widget.TextInputLayout

  • $|R_MYK3

    HI Ravi nice Tutorial working great But you add more features to it like Tabs / sliding Tabs it will be more cooler

  • Omar Hossam Ahmed

    Can someone tell me the difference between setting listSelector to @drawable/list_selector and settting the background of drawer_list_item to @drawable/list_selector. Which of these is going to show change in background colour upon selecting an item ?

  • Anu Patel

    Hello
    Navigation drawer is not Display proper in mi HM1s mobiles
    http://pasteboard.co/1q78MxSbl.png

    can any one Solved this ?

    • What is the problem in screenshot ?

      • Anu Patel

        it has shade beetween navigation drawer and activity.

  • sandypatel

    Hi, Ravi this is my Error
    Information:Gradle tasks [:app:compileDebugSources, :app:compileDebugAndroidTestSources]

  • Thanks a Lot Ravi

  • Raj

    I think in MainActivity.Java

    case R.id.home:

    should be

    case R.id.nav_home:

    Is it Correct or it has been done purposely ?

    • Yes, it should be. I don’t know how it got changed. Let me update it.

      Thanks for pointing that out 🙂

    • syam

      Yes, that’s is so right… I’ve been confusing all over the day why the one and only ‘Home’ on the navigation menu didn’t appeared on the right layout/content after been switching among the others navigation menu and it keeps leaving the previous navigation menu layout. It should be like the one below.

      case R.id.nav_home:
      navItemIndex = 0;
      CURRENT_TAG = TAG_HOME;
      break;

      • I guess this bug was update a longtime back.

  • johnny

    it shows some errors can we download the source code…or if that is been removed

    • I didn’t get your problem.

      • johnny

        there’s some issue with fragment …and m not able to download source code

  • sk

    this project not run properly

  • hrl

    i cant solve error in this project,…..

  • neha

    Ur dwnld links are not working,,i cant able to dwnld any of the projects

  • uslisha

    thanks Ravi, this really helpful >v<

  • sherwyn

    Thanx ravi and what should I put in manifest file ?

    • sherwyn

      I am using this in a existing project and the the app is crashing for some reason so if u can give me that info would reallh help

  • Osman Çetin

    Hi Ravi thanks for tutorial. I download your code and implement my project. But I have a problem. Other Activity for example AboutUsActivity give error this line.
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar() return null and gives error.

    • What is the theme of AboutUsActivity in manifest file?

      • Osman Çetin

        style.xml


        @color/colorPrimary
        @color/colorPrimaryDark
        @color/colorAccent
        false
        true

        false
        true

        AndroidManifest.xml

      • Osman Çetin

        what is your suggestion ?

        • If you added the toolbar in the layout, you need to apply NoAction bar theme to that activity.

  • Thorsten

    Hey Ravi nice work.
    I have a little issue.
    When i set the background color of the navigation drawer the “selected item highligher” disappears.
    So how can i set the background and highlighter color in a correct way?

      • Khaled Walid

        hello i need help in this article please
        in your Site http://www.androidhive.info/2014/12/android-uploading-camera-image-video-to-server-with-progress-bar/
        can you help me
        FATAL EXCEPTION: main

        Process: app.pro.Ebook.ebookers, PID: 22565

        java.lang.NullPointerException: file

        at android.net.Uri.fromFile(Uri.java:453)

        at app.pro.Ebook.ebookers.MainActivity2.getOutputMediaFileUri(MainActivity2.java:243)

        at app.pro.Ebook.ebookers.MainActivity2.captureImage(MainActivity2.java:128)

        at app.pro.Ebook.ebookers.MainActivity2.access$000(MainActivity2.java:22)

        at app.pro.Ebook.ebookers.MainActivity2$1.onClick(MainActivity2.java:69)

        at android.view.View.performClick(View.java:5698)

        at android.widget.TextView.performClick(TextView.java:10903)

        at android.view.View$PerformClick.run(View.java:22570)

        at android.os.Handler.handleCallback(Handler.java:739)

        at android.os.Handler.dispatchMessage(Handler.java:95)

        at android.os.Looper.loop(Looper.java:148)

        at android.app.ActivityThread.main(ActivityThread.java:7223)

        at java.lang.reflect.Method.invoke(Native Method)

        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)

        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)

        • evolver

          as far as I can see, you are trying to access a resource which is not present at the specified location.

      • Khaled Walid
      • Thorsten

        Perfect. Thank you.

  • SakilaTux

    Hi Sir @ravi8x:disqus i’m try to implement your tutorial in my project but i always have this error in my file app_bar_main
    Error:(13, 24) No resource found that matches the given name (at ‘theme’ with value ‘@style/AppTheme.AppBarOverlay’).
    I have already update my SDK tools ( google repository)
    i also modifie the bluid.gradle files but i still have this error.
    sorry for my english and thk for your help

    • evolver

      open your style resource. Check if there is any theme with name “Theme.AppBarOverlay”. if not found then replace it with any one of those already there.

  • Sander Bussink

    Hey Ravi thanks alot.
    I have one problem, when you switch from home to for example photos it loads the photos layout fine, but when you switch from any fragment back to home it doesn’t load the home layout. The problem is visible here: https://youtu.be/bIRRMBKB4Y0 .
    As you can see I added my own layout and some code but this problem is also there in the original app.
    Switching between any other fragment (for example between notifications and movies) works fine.

    Any help would be greatly appreciated.

    • When Calculator item is selected, you need to call these three lines

      navItemIndex = 0;
      CURRENT_TAG = TAG_HOME;
      loadHomeFragment();

      Are you doing it?

      • Sander Bussink

        I see the code doesn’t have loadHomeFragment(); :
        case R.id.nav_home:
        navItemIndex = 0;
        CURRENT_TAG = TAG_HOME;
        break;
        But the other fragments don’t have it either. I’ve fixed the issue by just removing the homefragment.

        A big thanks for your help though!

        • The method is there in MainActivity.java. Please recheck once.

          • Sander Bussink

            case R.id.home:
            navItemIndex = 0;
            CURRENT_TAG = TAG_HOME;
            loadHomeFragment();
            break;

            Tried this, doesn’t work. But I’ve fixed my problem so it’s alright, thanks for the help 🙂

          • Ok

          • Imam Muhtadi

            can you please share your solution? i’m stuck here

          • Sander Bussink

            Okay this is going to be hard to explain but here we go:
            I removed the homefragment all together so it didn’t appear in the navigation, first you have to make sure the homefragment is not used anywhere, or else the app won’t build. In mainactivity.java
            – at the top of the file remove private static finale String TAG_HOME = “home”;
            – at private Fragment getHomeFragment(), remove case 0 and change case 1 to case 0, case 2 to case 1 and so on. At default: change return new HomeFragment(); to return new PhotosFragment();
            – At private void setUpNavigationView() remove the case R.id.nav_home and again change the 1 to a 0, the 2 to a 1 and so on.
            – At if (shouldLoadHomeFragOnBackPress) change CURRENT_TAG = TAG_HOME; to CURRENT_TAG = TAG_PHOTOS;
            – at public boolean onCreateOptionsMenu(Menu menu) change navItemIndex == 3 to navItemIndex == 2
            – In the menu folder open activity_main_drawer.xml and remove

            I hope this helps, it is possible that I forgot something so please let me know and I will try to help you.

  • shivanee shinde

    I have this problem
    FATAL EXCEPTION: main
    Process: com.new.navigation, PID: 7060
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.new.navigation/com.new.navigation.activity.MainActivity}: android.view.InflateException: Binary XML file line #11: Binary XML file line #31: Error inflating class android.support.design.widget.FloatingActionButton
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
    at android.app.ActivityThread.-wrap11(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5417)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
    Caused by: android.view.InflateException: Binary XML file line #11: Binary XML file line #31: Error inflating class android.support.design.widget.FloatingActionButton
    at android.view.LayoutInflater.inflate(LayoutInflater.java:539)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
    at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:284)
    at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
    at com.shivaneeshindegmail.tradersdiary.activity.MainActivity.onCreate(MainActivity.java:71)
    at android.app.Activity.performCreate(Activity.java:6237)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
    at android.app.ActivityThread.-wrap11(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5417)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
    Caused by: android.view.InflateException: Binary XML file line #31: Error inflating class android.support.design.widget.FloatingActionButton
    at android.view.LayoutInflater.createView(LayoutInflater.java:645)
    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:764)
    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)
    at android.view.LayoutInflater.rInflate(LayoutInflater.java:835)
    at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798)
    at android.view.LayoutInflater.parseInclude(LayoutInflater.java:971)
    at android.view.LayoutInflater.rInflate(LayoutInflater.java:831)
    at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:515)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
    at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:284)
    at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
    at com.shivaneeshindegmail.tradersdiary.activity.MainActivity.onCreate(MainActivity.java:71)
    at android.app.Activity.performCreate(Activity.java:6237)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
    at android.app.ActivityThread.-wrap11(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5417)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
    Caused by: java.lang.reflect.InvocationTargetException
    at java.lang.reflect.Constructor.newInstance(Native Method)
    at android.view.LayoutInflater.createView(LayoutInflater.java:619)
    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:764)
    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)
    at android.view.LayoutInflater.rInflate(LayoutInflater.java:835)
    at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798)
    at android.view.LayoutInflater.parseInclude(LayoutInflater.java:971)
    at android.view.LayoutInflater.rInflate(LayoutInflater.java:831)
    at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:515)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
    at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:284)
    at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
    at com.shivaneeshindegmail.tradersdiary.activity.MainActivity.onCreate(MainActivity.java:71)
    at android.app.Activity.performCreate(Activity.java:6237)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
    at android.app.ActivityThread.-wrap11(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5417)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
    Caused by: java.lang.NoSuchMethodError: No direct method (Landroid/widget/ImageView;Landroid/support/v7/widget/AppCompatDrawableManager;)V in class Landroid/support/v7/widget/AppCompatImageHelper; or its super classes (declaration of ‘android.support.v7.widget.AppCompatImageHelper’ appears in /data/data/com.shivaneeshindegmail.tradersdiary/files/instant-run/dex/slice-com.android.support-appcompat-v7-24.2.1_88b13b48877332c20d2d0b34783d7f419507e2d6-classes.dex)
    at android.support.design.widget.FloatingActionButton.(FloatingActionButton.java:170)
    at android.support.design.widget.FloatingActionButton.(FloatingActionButton.java:147)
    at java.lang.reflect.Constructor.newInstance(Native Method)
    at android.view.LayoutInflater.createView(LayoutInflater.java:619)
    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:764)
    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)
    at android.view.LayoutInflater.rInflate(LayoutInflater.java:835)
    at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798)
    at android.view.LayoutInflater.parseInclude(LayoutInflater.java:971)
    at android.view.LayoutInflater.rInflate(LayoutInflater.java:831)
    at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:515)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
    at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:284)
    at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
    at com.new.navigate.activity.MainActivity.onCreate(MainActivity.java:71)
    at android.app.Activity.performCreate(Activity.java:6237)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
    at android.app.ActivityThread.-wrap11(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5417)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

  • Team Mondays

    Hi Ravi, Can you help me how to add dynamic menu item and sub menu items to navigation drawer layout?

  • Ziigic

    You are Awesome….

  • Luong Tri Dung

    must implement OnFragmentInteractionListener
    at fragment.HomeFragment.onAttach(HomeFragment.java:84)
    can you tell me what is this error?

    • In your new fragment, comment code in onAttach() method.

  • Bilal Khalid

    Hello Ravi your code is very useful but the only issue is, When we add some data into fragment, It makes the application very slow, Also switching between fragments are not smooth sometimes it switch and sometime its not.
    Any suggestion ?

    • How much data you are loading in Fragment. Also make sure that you are not having any code that is running in loops.

  • riyaz ahmed

    how can i change profile pic??

    • In MainActivity there is a url of profile pic, you have to change that or you can load a local image from sdcard.

      • riyaz ahmed

        how to load a local image from sd card.

  • Rizwan Khan

    how can i add mre textview to menu like number

  • Asad Saeed Awan

    How do I add same navigation drawer in different activities?

  • riyaz ahmed

    I just changed the layout of home fragment but when i go to home from any other activity(photos,movies,notification), it shows me previous home layout that i changed.

    • Mahmoud Al-Harooney

      I have the same problem here did you find the solution??

      • riyaz ahmed

        no bro.

        • Kamil Buczel

          Hey, here is a one way of fixing it:
          1. Declare class variable: public static int currentMenuID = -1;

          2. In loadHomeFragment() comment (or delete):
          if (getSupportFragmentManager().findFragmentByTag(CURRENT_TAG) != null) {
          drawer.closeDrawers();

          // show or hide the fab button
          toggleFab();
          return;
          }

          3. In onNavigationItemSelected change “loadHomeFragment();”
          (on bottom, before return) to:

          if (currentMenuID != menuItem.getItemId()) {
          loadHomeFragment();
          } else {
          drawer.closeDrawers();
          }

          currentMenuID = menuItem.getItemId();

          Happy coding!

        • Kamil Buczel

          Another, simpler one (:P) is changing case R.id.home: to case R.id.nav_home:

          It seems that tutorial was updated but downloadable code wasn’t.

          • Okay. I’ll check downloaded code too. Thank you.

  • Abdelkrim KHALDI

    Great work Ravi. There is just a problem on orientation change, the title of the bar become the application name.

  • Ahmar Ali Khan

    Sir Where is the coding of all fragment class..I have some error in the fragment objects..
    plz rply soon..

  • Ahmar Ali Khan

    And also AboutUsActivity class And PrivacyPolicyActivity Class and also xml file

    • Abdelkrim KHALDI

      Click “Download Code” in the beggining of the tutorial you will have all the sources.

  • Sanket

    Need help with this error:

    E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.haplotech.navdrawerapp, PID: 2508
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.haplotech.navdrawerapp/com.haplotech.navdrawerapp.activity.MainActivity}: java.lang.IllegalStateException: This Activity already has an action bar supplied by the window decor. Do not request Window.FEATURE_SUPPORT_ACTION_BAR and set windowActionBar to false in your theme to use a Toolbar instead.
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
    at android.app.ActivityThread.access$800(ActivityThread.java:144)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:135)
    at android.app.ActivityThread.main(ActivityThread.java:5221)
    at java.lang.reflect.Method.invoke(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:372)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
    Caused by: java.lang.IllegalStateException: This Activity already has an action bar supplied by the window decor. Do not request Window.FEATURE_SUPPORT_ACTION_BAR and set windowActionBar to false in your theme to use a Toolbar instead.
    at android.support.v7.app.AppCompatDelegateImplV9.setSupportActionBar(AppCompatDelegateImplV9.java:199)
    at android.support.v7.app.AppCompatActivity.setSupportActionBar(AppCompatActivity.java:130)
    at com.haplotech.navdrawerapp.activity.MainActivity.onCreate(MainActivity.java:72)
    at android.app.Activity.performCreate(Activity.java:5933)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
    at android.app.ActivityThread.access$800(ActivityThread.java:144)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:135)
    at android.app.ActivityThread.main(ActivityThread.java:5221)
    at java.lang.reflect.Method.invoke(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:372)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

    • Remove theme attribute for MainActivity from manifest file.

  • Mithun S

    How can i call Function and fill data inside Settings Page? Whether i should it call from Fragment itself or from Parent Activity. Please Explain that

  • Pouya Mansournia

    Hey Ravi nice work <3
    I have a little issue.
    I put the button in photos fragment and when pressed Button go to other page !
    where i do put for my code ?
    where photos fragment.java ?
    Please help me.

    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (getArguments() != null) {
    mParam1 = getArguments().getString(ARG_PARAM1);
    mParam2 = getArguments().getString(ARG_PARAM2);
    }

    Button btn = (Button)findViewById(R.id.a_button); <<<<< Not findViewByid

    }

  • Pouya Mansournia

    Hey Ravi thanks alot for Tutorial
    I have one problem,
    when put the button box in fragment phots xml file for change any text for example if method for Toast view. I shoud put the if code to photoesfragment.java but when i called method to Oncreat not work or not findViewByID Method !!!

    for example :

    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (getArguments() != null) {
    mParam1 = getArguments().getString(ARG_PARAM1);
    mParam2 = getArguments().getString(ARG_PARAM2);
    }

    Button btn = (Button)findViewById(R.id.a_button); <<<<<< Not put findViewByid

    }

  • Pouya Mansournia

    Hey Ravi thanks alot for Tutorial
    I have one problem,
    when put the button box in fragment phots xml file for change any text for example if method for Toast view. I shoud put the if code to photoesfragment.java but when i called method to Oncreat not work or not findViewByID Method !!!

    please help me

    for example :

    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (getArguments() != null) {
    mParam1 = getArguments().getString(ARG_PARAM1);
    mParam2 = getArguments().getString(ARG_PARAM2);
    }

    Button btn = (Button)findViewById(R.id.a_button); <<<<<< Not put findViewByid

    }

    • findViewById should be used in onCreateView() method in fragment.

  • Raju Thomas

    Hi Ravi, please tell me how to open card view when selecting one of the fragments(just like google play sore, while selecting an item from navigation drawer will open a card view of apps). I tried to do it the same way as activity but not working..

  • Sachin Warad

    i am getting error unfortunately app is not working.. can anyone help me plzzzzz

  • Le Nguyen

    Good demo! Thank u so much

  • Asad Saeed Awan

    Sir I have implemented this tutorial to my app few days ago. It was working fine. I am using Nexus 6 so Android 7.0 update came today and I have installed this update. After this when I open navigation drawer its header is missing. Please see picture for reference. https://uploads.disquscdn.com/images/0f26a90a2b914a6f24e4e1ff95f9ae81ee749c645be27eca68a79f090749da08.png

    • What the header should contain actually? I can see some text there, may be background color / image is missing.

      • Asad Saeed Awan

        Sorry Sir it was my mistake. Mobile Wifi was turned off so it wasn’t loading profile and background images from the URL you had given in tutorial. Sorry once again.

        • Flash Alerts

          add

  • androidlearner

    Sir I have a question. I have implemented a navigation drawer and login page.After login successfully I want to navigated to the navigation drawer. I did that.the navigation drawer there is a menu called profile.When I click the profile menu I it shows the profile page and it contains log out button.When I click that logout button my app is stopped.There is an exception like below,

    java.lang.IllegalArgumentException: No view found for id 0x7f0c006d

  • Niladri Bhusan Mishra

    what do I put in style.xml file

  • Bagues Danang S

    nice tutorial

  • anand yadav

    Hi ravi,
    I am trying to make customized actionbar/toolbar. plz help me.

  • Abdur Rafay

    Hello sir, i am getting this error. Any help would be highly appreciated, thankyou.
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.adolfhipster.thesavingsjar/com.example.adolfhipster.thesavingsjar.activity.HomeActivity}: java.lang.NullPointerException: Attempt to invoke virtual method ‘android.view.View android.support.design.widget.NavigationView.getHeaderView(int)’ on a null object reference

  • Manil

    Hi Ravi, Thanks a lot for publishing this project. In the provided code, shouldn’t the first switch statement in setUpNavigationView() be “case R.id.nav_home:” rather than “case R.id.home:”?

    • Manil

      Ah! I noticed that its “nav_home” in the code mentioned on the website, seems like a minor error in the attached code.

  • Gaurav meghanathi

    i want to create navigation drawer look like with expand not each and every title some specific
    only.https://play.google.com/store/apps/details?id=com.sttl.vibrantgujarat&hl=en

  • Michael Cardoza

    Quick question about the material design buttons, where and how do I put them into the app? I simply drag and dropped the folders into the res file but that was obviously wrong. Help would be greatly appreciated.

  • Uday Kumar Chaduvula

    https://uploads.disquscdn.com/images/6e5c254973ed71754c7ba53eb51b30e7a584c92ebff0b6ed988a5cc9e2249875.png https://uploads.disquscdn.com/images/cd1d0d978d9853b570aaefbec125b14c74106bdfb30fff5ea49cc947ef873f99.png hii sir i have a problem that whenever i put any button or text view in content_main it shows in another fragments as a background how to resolve it

  • EspressoK

    when i click on Photos, the Photo Fragment appears as expected. When i click on Movies, the Movies Fragment appears as well. But when i am on Movies Fragment and then click on the Photos Fragment, the Photo Fragment does not appear. Instead, the Movies Fragment appears. How can i solve this?

  • Atula

    hello @Ravi,
    I need to know that can we create a navigation drawer which remain fixed and the main content get swipped and the navigation drawer remain at the back of main content…?

    • shikher

      that is not called navigation drawer, that is simple fragments game.

  • Manisha Khatke

    hello ravi,
    I want to add swiping tab layout in front screen?
    What should i do ?

  • Dmitry Novikov

    Hi Ravi! Thanks a lot! Cool and useful example!

  • Deyraka

    Hello @ravi8x:disqus , I’ve tried your tutorial. But, I got an error while I debug the code. here is the errror : java.lang.RuntimeException: com.ipds.googlesignin.activity.MainActivity@38af72a2 must implement OnFragmentInteractionListener
    at com.ipds.googlesignin.fragment.HomeFragment.onAttach(HomeFragment.java:84). I don’t what should I do. Can you renew the link for the project code? because I’ve tried to download it but I got nothing. thanks

  • Thillai K

    Hi @Ravi,

    Is it possible to implement expandable list view for a single drawer item in the navigation drawer menu?

  • shikher

    It is a very nice demo to create a Navigation Drawer Ravi.

  • rayven

    Most usefull demo thnx brother and keep it up .
    Iam a new learner of android and i need some questions and doubts to ask u can i get any contact of yours

  • vahid hasani

    Hi Ravi tanx for great tutorial. I have a problem in this tutorial. when i move between fragments and i try to return to home fragment in app the floating button is there but layout is not home layout. So i tried with ur apk file too but there was the problem too.focus on layout background icon. tanx again and please help to solve it.

  • rahul agrawal

    Hi Ravi, thanks for the tutorial.
    Can you please help me with correct steps on how to add sub menu on menu item click with collapse/expand sliding effect.

  • sameer khan

    Hi Ravi Image is not saved once the activity is closed and start again, How to achieve it with shared preferences

    • Which image you are talking about?

      • sameer khan

        @ravi8x:disqus I am talking about the profile image it is not saved while the app restart and I did this but not working http://stackoverflow.com/questions/41041119/image-saved-in-preferences-is-not-loading-picture-oncreate-method?noredirect=1#comment69290189_41041119

      • sameer khan

        @ravi8x:disqus my comments is not getting approval from android hive I am not able to comment anything here. What do I do?

        • sameer khan

          @ravi8x:disqus I wanted to share a link but I guess android hive is not giving approval for it. Well, I was talking about profile picture after app restart again I am not able to see the uploaded image I tried with shared preferences to store picture path but I guess I am doing wrong something. I wish I could share my code.

          • sameer khan

            Ravi Tamada I did it….Please see and everyone refer : first get preferences with sharedpreferences object defined globally and in onActivityResult do this after loading image with glide “sp.edit().putString(“dp”, picturePath).apply();”
            now check if it has a “dp” ….”boolean path =sp.contains(“dp”);” and last do this

            if(path) {

            String value=sp.getString(“dp”,picturePath);

            Glide.with(this).load(value)

            .crossFade()

            .thumbnail(0.5f)

            .bitmapTransform(new CircleTransform(this))

            .diskCacheStrategy(DiskCacheStrategy.ALL)

            .into(profimg);

            }

  • sameer khan

    Ravi one last thing, this glide is not working for lollipop and above version its working perfectly in kitkat when I upload my image it shows blank nothing just the background of nav header image doesn’t load with glide if version is lollipop and above

    • John Cole

      Check your permissions and make sure you have this
      It should work now. Also read on implementing the new permissions system from lollipop and above

  • Martin Mbaabu

    Hey Ravi, thanks again for the great work you do here. Android programming has never been so easy to understand. One thing I would like to ask were is the drawer_layout resource you reference with the line drawer = (DrawerLayout) findViewById(R.id.drawer_layout); in the main activity

    • Check once again. It’s there in 16th point code.

  • Hieu Luu

    I’m getting fragment overlapping problem with both your code and apk file. For example, when I select home from menu after switched to other fragments the home fragment doesn’t replace existing fragment in “R.id.frame” layout, it only replace fab and menu title. Please help, thank you!

    • Hieu Luu

      Ok, I found the problem and solved it, just replace “R.id.home” in “switch (menuItem.getItemId()) { case R.id.home:” with “R.id.nav_home”. You fix it in the tutorial but haven’t fix it in download files.

      One more question: why would you use “commitAllowingStateLoss()” instead of plain “commit()”?
      Thank in advance!

  • Bongga

    Hey Ravi. Let me tell you I love this tutorial. It helps me a lot. Thanks man.

  • Asmaa

    W/System﹕ ClassLoader referenced unknown path: /data/app/com.example.hp.navigationdrawer-2/lib/arm64
    it closes after opening immediately

  • Indirajith

    Application force closing automatically. Its showing nothing in error log also…

    • Android Studio might lost debugging connection. Try removing and connecting device again.

  • juna.binrusdi

    Hey Ravi, this is great tutorial, Thanks bro..

  • Subham Verma

    Hello Ravi ,this is the nice tutorial but one problme in my project Navigation item are not scroll.

  • לירן מעתוק

    Hi Ravi, thanks on the tutorial.
    I need your help.
    I don’t know why, I copied all the content but I get null at this if

    if (getSupportFragmentManager().findFragmentByTag(CURRENT_TAG) != null) {

    I really don’t know what happend, I downloaded your code and it’s worked, but at my project that only contains your code it’s not working.
    Waiting for your answer.

    • Can you paste the exception log here.

      • לירן מעתוק

        12-28 12:37:03.486 3385-3385/? I/art: Not late-enabling -Xcheck:jni (already on)
        12-28 12:37:03.487 3385-3385/? W/art: Unexpected CPU variant for X86 using defaults: x86_64
        12-28 12:37:03.641 3385-3385/liran.cookers W/System: ClassLoader referenced unknown path: /data/app/liran.cookers-1/lib/x86_64
        12-28 12:37:03.682 3385-3385/liran.cookers I/InstantRun: Instant Run Runtime started. Android package is liran.cookers, real application class is null.
        12-28 12:37:15.329 3385-3385/liran.cookers W/System: ClassLoader referenced unknown path: /data/app/liran.cookers-1/lib/x86_64
        12-28 12:37:15.649 3385-3385/liran.cookers W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
        12-28 12:37:15.899 3385-3385/liran.cookers D/TAG: no have this fragment FragmentManager{205e4b in HostCallbacks{667500f}}
        12-28 12:37:15.906 3385-3385/liran.cookers D/AndroidRuntime: Shutting down VM
        12-28 12:37:15.907 3385-3385/liran.cookers E/AndroidRuntime: FATAL EXCEPTION: main
        Process: liran.cookers, PID: 3385
        java.lang.RuntimeException: Unable to start activity ComponentInfo{liran.cookers/liran.cookers.activity.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method ‘int java.lang.String.hashCode()’ on a null object reference
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2665)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
        at android.app.ActivityThread.-wrap12(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6119)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
        Caused by: java.lang.NullPointerException: Attempt to invoke virtual method ‘int java.lang.String.hashCode()’ on a null object reference
        at com.bumptech.glide.load.engine.EngineKey.hashCode(EngineKey.java:109)
        at sun.misc.Hashing.singleWordWangJenkinsHash(Hashing.java:48)
        at java.util.HashMap.put(HashMap.java:423)
        at com.bumptech.glide.load.engine.Engine.load(Engine.java:184)
        at com.bumptech.glide.request.GenericRequest.onSizeReady(GenericRequest.java:449)
        at com.bumptech.glide.request.target.ViewTarget$SizeDeterminer.getSize(ViewTarget.java:211)
        at com.bumptech.glide.request.target.ViewTarget.getSize(ViewTarget.java:100)
        at com.bumptech.glide.request.GenericRequest.begin(GenericRequest.java:272)
        at com.bumptech.glide.request.ThumbnailRequestCoordinator.begin(ThumbnailRequestCoordinator.java:87)
        at com.bumptech.glide.manager.RequestTracker.resumeRequests(RequestTracker.java:83)
        at com.bumptech.glide.RequestManager.resumeRequests(RequestManager.java:180)
        at com.bumptech.glide.RequestManager.onStart(RequestManager.java:203)
        at com.bumptech.glide.manager.ActivityFragmentLifecycle.onStart(ActivityFragmentLifecycle.java:50)
        at com.bumptech.glide.manager.SupportRequestManagerFragment.onStart(SupportRequestManagerFragment.java:135)
        at android.support.v4.app.Fragment.performStart(Fragment.java:2210)
        at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1337)
        at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1523)
        at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1585)
        at android.support.v4.app.FragmentManagerImpl.dispatchStart(FragmentManager.java:2837)
        at android.support.v4.app.FragmentController.dispatchStart(FragmentController.java:212)
        at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:613)
        at android.support.v7.app.AppCompatActivity.onStart(AppCompatActivity.java:181)
        at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1248)
        at android.app.Activity.performStart(Activity.java:6696)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2628)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
        at android.app.ActivityThread.-wrap12(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6119)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

      • לירן מעתוק

        java.lang.NullPointerException: Attempt to invoke virtual method ‘int java.lang.String.hashCode()’ on a null object reference

        • לירן מעתוק

          the full exception log cant posted here casue the web need to approve it .
          anyone , i think that u need this line.. i really need your help becasue its for project that realy importent . thank u from ahead.

  • Nova Leary

    Hey Ravi, thanks for the tutorial! I have everything fully working but I have one
    crucial question.. how do I add in the button on the side like this
    picture attached and it make switch the items in the navigation drawer to a
    different set of items? I’m trying to make an account management
    interface in the navigation drawer like how Google+ has it.

    This is the picture
    https://uploads.disquscdn.com/images/2b22d54a218acf9ad0fcade87be61372255507b25b88027422bee5d5f7d18499.png

    • See if you can load a Fragment in navigation view header section. Using fragment you can control the header part easily.

      • Nova Leary

        For some reason I’m trying to reply but my posts keep on getting halted and ‘checked’ by Android Hive.. not sure why though. But it looks like Android Hive eventually rejects my post and doesn’t give me a reason why ._.

        • Normally external links in comments won’t be approved unless I approve manually.

          • Nova Leary

            Oh, well that explains why it wasn’t posting my stuff immediately. And I did try using the libraries.. But they made thing even more confusing for me

          • Yeah, stick to navigation view. Try posting question in stackoverflow (mention without using third party libraries).

      • Nova Leary

        I was trying to say this:

        I’m watching a tutorial on implementing the drawer using fragments right now.. I did try something like this though: https://github.com/NovaViper/TrinityLocker

        But once I finish following this tutorial, I’ll let you know the results of the fragments

        —EDIT—

        I actually just found a [library](https://github.com/mikepenz/Ma… that utilizes the account headers. And the tutorial only talks about the fragments for the actual drawer, not the header.

  • nolonger theroad

    Hi sir.
    I want to click About Us menu for show textview
    but when i click my app has stopped again and again .
    how to solve it .
    Would it be a bother if help me please ~~~

  • Subham

    Hi Sir
    Drawer Item not scroll .How to solve this problem.

  • CLOUDit Kenya

    Hi there! I encountered a small difference between the outlined tutorial and the downloaded source code. (attached). And when I change my id to nav_home, the home fragment does not close when you tap another frag e.g photos fragment and ends up overlaying another frag, Also with the id as ‘home’, when you tap the home fragment while on another one, it does not load it as the id of the home fragment is ‘nav_home’.

    kindly expound… thanks. https://uploads.disquscdn.com/images/a85138f8fb539157078f4e1aecd2e14db7db887c297fa60b9a2c89d96e07bc4d.png

    • amin

      thank you so much!!!

  • Anshul

    Hi there! how i change background colour of items in drawer when I hover on particular item

  • minijordon

    How do you change the hamburger icon? I tried changing “toolbar” to “R.drawable.myicon” in

    ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.openDrawer, R.string.closeDrawer)

    but it wouldn’t accept my input

  • akila mani

    File like FragmentHome,AboutUsActivity are missing where to find it

  • akila mani

    by download i got the file

  • akila mani

    but only home is coming

  • akila mani

    i have done it
    thank you

  • Vishal

    can you tell me how to add custom icons for menu items in navigation drawer.. , my own images.?

  • Sparker0i

    Just one bug Ravi Sir, the user icon inside the circle and the backgeound of the ImageView in the drawer does not load (PS. Same file as yours, copy-pasted…Do help)

  • Bhaskar

    Ravi, the other classes are not defined in the above code. Also, the code is not getting downloaded

  • Akshay Shetty

    Why did you create seperate activities of “about us” and “privacy policy” in the navigation drawer instead of fragments?
    how do I know when to use fragments or activity and can I perform all the operations in a fragment that i can in an activity for example Onclicklistener operations and moving to a new screen from a fragment to another screen
    I really want to know..thanks

  • לירן מעתוק

    Hey Ravi , how do i change fragments from fragment , and not from mainActivity..?
    thanks for your help..

  • Neeraja

    Hi Ravi, I’m using Navigation drawer activities in one of my projects. The toolbar appears as transparent on android 4.4 devices though, I have set a colour to it. It looks fine on lollipop and above versions. How can I fix this?

  • Andi Syarif

    hello all
    any body can help me to convert my activity to fragment because i want to use navigation drawer listview json php mysql

    this is my code

    package com.andicom.andi;

    import android.app.AlertDialog;
    import android.app.Fragment;
    import android.app.FragmentManager;
    import android.app.FragmentTransaction;
    import android.content.DialogInterface;
    import android.os.Bundle;
    import android.support.design.widget.FloatingActionButton;
    import android.support.v4.widget.SwipeRefreshLayout;
    import android.support.v7.app.AppCompatActivity;
    import android.support.v7.widget.Toolbar;
    import android.util.Log;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.AdapterView;
    import android.widget.EditText;
    import android.widget.ListView;
    import android.widget.RelativeLayout;
    import android.widget.Toast;

    import com.andicom.andi.adapter.AdapterAdmin;
    import com.android.volley.Request;
    import com.android.volley.Response;
    import com.android.volley.VolleyError;
    import com.android.volley.VolleyLog;
    import com.android.volley.toolbox.JsonArrayRequest;
    import com.android.volley.toolbox.StringRequest;
    import com.andicom.andi.app.AppControllerAdmin;
    import com.andicom.andi.data.DataAdmin;
    import com.andicom.andi.util.ServerAdmin;

    import org.json.JSONArray;
    import org.json.JSONException;
    import org.json.JSONObject;

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

    public class MainActivityAdmin extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener {

    Toolbar toolbar;
    FloatingActionButton fab;
    ListView list;
    SwipeRefreshLayout swipe;
    List itemList = new ArrayList();
    AdapterAdmin adapterAdmin;
    int success;
    AlertDialog.Builder dialog;
    LayoutInflater inflater;
    View dialogView;
    EditText txt_id, txt_namapengguna, txt_pass, txt_email;
    String id, namapengguna, pass, email;

    private static final String TAG = MainActivityAdmin.class.getSimpleName();

    private static String url_select = ServerAdmin.URL + “select.php”;
    private static String url_insert = ServerAdmin.URL + “insert.php”;
    private static String url_edit = ServerAdmin.URL + “edit.php”;
    private static String url_update = ServerAdmin.URL + “update.php”;
    private static String url_delete = ServerAdmin.URL + “delete.php”;

    public static final String TAG_ID = “id”;
    public static final String TAG_NAMAPENGGUNA = “namapengguna”;
    public static final String TAG_PASS = “pass”;
    public static final String TAG_EMAIL = “email”;
    private static final String TAG_SUCCESS = “success”;
    private static final String TAG_MESSAGE = “message”;

    String tag_json_obj = “json_obj_req”;

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

    // menghubungkan variablel pada layout dan pada java
    fab = (FloatingActionButton) findViewById(R.id.fab_add);
    swipe = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);
    list = (ListView) findViewById(R.id.list);

    // untuk mengisi data dari JSON ke dalam adapterAdmin
    adapterAdmin = new AdapterAdmin(MainActivityAdmin.this, itemList);
    list.setAdapter(adapterAdmin);

    // menamilkan widget refresh
    swipe.setOnRefreshListener(this);

    swipe.post(new Runnable() {
    @Override
    public void run() {
    swipe.setRefreshing(true);
    itemList.clear();
    adapterAdmin.notifyDataSetChanged();
    callVolley();
    }
    }
    );

    // fungsi floating action button memanggil form kontak
    fab.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
    DialogForm(“”, “”, “”,””, “SIMPAN”);
    }
    });

    // listview ditekan lama akan menampilkan dua pilihan edit atau delete data
    list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {

    @Override
    public boolean onItemLongClick(final AdapterView parent, View view,
    final int position, long id) {
    // TODO Auto-generated method stub
    final String idx = itemList.get(position).getId();

    final CharSequence[] dialogitem = {“Edit”, “Delete”};
    dialog = new AlertDialog.Builder(MainActivityAdmin.this);
    dialog.setCancelable(true);
    dialog.setItems(dialogitem, new DialogInterface.OnClickListener() {

    @Override
    public void onClick(DialogInterface dialog, int which) {
    // TODO Auto-generated method stub
    switch (which) {
    case 0:
    edit(idx);
    break;
    case 1:
    delete(idx);
    break;
    }
    }
    }).show();
    return false;
    }
    });

    }

    @Override
    public void onRefresh() {
    itemList.clear();
    adapterAdmin.notifyDataSetChanged();
    callVolley();
    }

    // untuk mengosongi edittext pada form
    private void kosong(){
    txt_id.setText(null);
    txt_namapengguna.setText(null);
    txt_pass.setText(null);
    txt_email.setText(null);
    }

    // untuk menampilkan dialog from kontak
    private void DialogForm(String idx, String namax, String passx, String emailx, String button) {
    dialog = new AlertDialog.Builder(MainActivityAdmin.this);
    inflater = getLayoutInflater();
    dialogView = inflater.inflate(R.layout.form_admin, null);
    dialog.setView(dialogView);
    dialog.setCancelable(true);
    dialog.setIcon(R.mipmap.ic_launcher);
    dialog.setTitle(“Form Biodata”);

    txt_id = (EditText) dialogView.findViewById(R.id.txt_id);
    txt_namapengguna = (EditText) dialogView.findViewById(R.id.txt_namapengguna);
    txt_pass = (EditText) dialogView.findViewById(R.id.txt_pass);
    txt_email = (EditText) dialogView.findViewById(R.id.txt_email);

    if (!idx.isEmpty()){
    txt_id.setText(idx);
    txt_namapengguna.setText(namax);
    txt_pass.setText(passx);
    txt_email.setText(emailx);
    } else {
    kosong();
    }

    dialog.setPositiveButton(button, new DialogInterface.OnClickListener() {

    @Override
    public void onClick(DialogInterface dialog, int which) {
    id = txt_id.getText().toString();
    namapengguna = txt_namapengguna.getText().toString();
    pass = txt_pass.getText().toString();
    email = txt_email.getText().toString();

    simpan_update();
    dialog.dismiss();
    }
    });

    dialog.setNegativeButton(“BATAL”, new DialogInterface.OnClickListener() {

    @Override
    public void onClick(DialogInterface dialog, int which) {
    dialog.dismiss();
    kosong();
    }
    });

    dialog.show();
    }

    // untuk menampilkan semua data pada listview
    private void callVolley(){
    itemList.clear();
    adapterAdmin.notifyDataSetChanged();
    swipe.setRefreshing(true);

    // membuat request JSON
    JsonArrayRequest jArr = new JsonArrayRequest(url_select, new Response.Listener() {
    @Override
    public void onResponse(JSONArray response) {
    Log.d(TAG, response.toString());

    // Parsing json
    for (int i = 0; i < response.length(); i++) {
    try {
    JSONObject obj = response.getJSONObject(i);

    DataAdmin item = new DataAdmin();

    item.setId(obj.getString(TAG_ID));
    item.setNama(obj.getString(TAG_NAMAPENGGUNA));
    item.setPass(obj.getString(TAG_PASS));
    item.setEmail(obj.getString(TAG_EMAIL));

    // menambah item ke array
    itemList.add(item);
    } catch (JSONException e) {
    e.printStackTrace();
    }
    }

    // notifikasi adanya perubahan data pada adapterAdmin
    adapterAdmin.notifyDataSetChanged();

    swipe.setRefreshing(false);
    }
    }, new Response.ErrorListener() {

    @Override
    public void onErrorResponse(VolleyError error) {
    VolleyLog.d(TAG, "Error: " + error.getMessage());
    swipe.setRefreshing(false);
    }
    });

    // menambah request ke request queue
    AppControllerAdmin.getInstance().addToRequestQueue(jArr);
    }

    // fungsi untuk menyimpan atau update
    private void simpan_update() {
    String url;
    // jika id kosong maka simpan, jika id ada nilainya maka update
    if (id.isEmpty()){
    url = url_insert;
    } else {
    url = url_update;
    }

    StringRequest strReq = new StringRequest(Request.Method.POST, url, new Response.Listener() {

    @Override
    public void onResponse(String response) {
    Log.d(TAG, “Response: ” + response.toString());

    try {
    JSONObject jObj = new JSONObject(response);
    success = jObj.getInt(TAG_SUCCESS);

    // Cek error node pada json
    if (success == 1) {
    Log.d(“Add/update”, jObj.toString());

    callVolley();
    kosong();

    Toast.makeText(MainActivityAdmin.this, jObj.getString(TAG_MESSAGE), Toast.LENGTH_LONG).show();
    adapterAdmin.notifyDataSetChanged();

    } else {
    Toast.makeText(MainActivityAdmin.this, jObj.getString(TAG_MESSAGE), Toast.LENGTH_LONG).show();
    }
    } catch (JSONException e) {
    // JSON error
    e.printStackTrace();
    }

    }
    }, new Response.ErrorListener() {

    @Override
    public void onErrorResponse(VolleyError error) {
    Log.e(TAG, “Error: ” + error.getMessage());
    Toast.makeText(MainActivityAdmin.this, error.getMessage(), Toast.LENGTH_LONG).show();
    }
    }) {

    @Override
    protected Map getParams() {
    // Posting parameters ke post url
    Map params = new HashMap();
    // jika id kosong maka simpan, jika id ada nilainya maka update
    if (id.isEmpty()){
    params.put(“namapengguna”, namapengguna);
    params.put(“pass”, pass);
    params.put(“email”, email);
    } else {
    params.put(“id”, id);
    params.put(“namapengguna”, namapengguna);
    params.put(“pass”, pass);
    params.put(“email”, email);
    }

    return params;
    }

    };

    AppControllerAdmin.getInstance().addToRequestQueue(strReq, tag_json_obj);
    }

    // fungsi untuk get edit data
    private void edit(final String idx){
    StringRequest strReq = new StringRequest(Request.Method.POST, url_edit, new Response.Listener() {

    @Override
    public void onResponse(String response) {
    Log.d(TAG, “Response: ” + response.toString());

    try {
    JSONObject jObj = new JSONObject(response);
    success = jObj.getInt(TAG_SUCCESS);

    // Cek error node pada json
    if (success == 1) {
    Log.d(“get edit data”, jObj.toString());
    String idx = jObj.getString(TAG_ID);
    String namapenggunax = jObj.getString(TAG_NAMAPENGGUNA);
    String passx = jObj.getString(TAG_PASS);
    String emailx = jObj.getString(TAG_EMAIL);

    DialogForm(idx, namapenggunax, passx, emailx, “UPDATE”);

    adapterAdmin.notifyDataSetChanged();

    } else {
    Toast.makeText(MainActivityAdmin.this, jObj.getString(TAG_MESSAGE), Toast.LENGTH_LONG).show();
    }
    } catch (JSONException e) {
    // JSON error
    e.printStackTrace();
    }

    }
    }, new Response.ErrorListener() {

    @Override
    public void onErrorResponse(VolleyError error) {
    Log.e(TAG, “Error: ” + error.getMessage());
    Toast.makeText(MainActivityAdmin.this, error.getMessage(), Toast.LENGTH_LONG).show();
    }
    }) {

    @Override
    protected Map getParams() {
    // Posting parameters ke post url
    Map params = new HashMap();
    params.put(“id”, idx);

    return params;
    }

    };

    AppControllerAdmin.getInstance().addToRequestQueue(strReq, tag_json_obj);
    }

    // fungsi untuk menghapus
    private void delete(final String idx){
    StringRequest strReq = new StringRequest(Request.Method.POST, url_delete, new Response.Listener() {

    @Override
    public void onResponse(String response) {
    Log.d(TAG, “Response: ” + response.toString());

    try {
    JSONObject jObj = new JSONObject(response);
    success = jObj.getInt(TAG_SUCCESS);

    // Cek error node pada json
    if (success == 1) {
    Log.d(“delete”, jObj.toString());

    callVolley();

    Toast.makeText(MainActivityAdmin.this, jObj.getString(TAG_MESSAGE), Toast.LENGTH_LONG).show();

    adapterAdmin.notifyDataSetChanged();

    } else {
    Toast.makeText(MainActivityAdmin.this, jObj.getString(TAG_MESSAGE), Toast.LENGTH_LONG).show();
    }
    } catch (JSONException e) {
    // JSON error
    e.printStackTrace();
    }

    }
    }, new Response.ErrorListener() {

    @Override
    public void onErrorResponse(VolleyError error) {
    Log.e(TAG, “Error: ” + error.getMessage());
    Toast.makeText(MainActivityAdmin.this, error.getMessage(), Toast.LENGTH_LONG).show();
    }
    }) {

    @Override
    protected Map getParams() {
    // Posting parameters ke post url
    Map params = new HashMap();
    params.put(“id”, idx);

    return params;
    }

    };

    AppControllerAdmin.getInstance().addToRequestQueue(strReq, tag_json_obj);
    }
    }

    Regard’s

  • Kumararaja

    Hi, i get an error “No resource found that matches the given name(at ‘icon’ with
    value’@drawable/ic_home_black_24dp’)

    • Kumararaja

      Error Cleared

    • sirvan

      Hi too

      You must add icon to your project and next use them for set Icon in xml.
      With vector assest in android studio, and click right an res folder and next choice vector assest or image assest , and next create icon for your app.

      • Kumararaja

        Yes, I have cleared the error but i have met a another crash error noted and these are,

        Error while executing: am start -n “com.example.kumar.navigation_final/com.example.kumar.navigation_final.activity.MainActivity” -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
        Starting: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] cmp=com.example.kumar.navigation_final/.activity.MainActivity }
        Error type 3
        Error: Activity class {com.example.kumar.navigation_final/com.example.kumar.navigation_final.activity.MainActivity} does not exist.

        Error while Launching activity “

  • Satyendra Singh

    how to create a notifications.xml and main.xml files in step 5.

    • Kumararaja

      Create Xml file as, Layout Xml file and move it to Menu package.

  • Abhishek Aggarwal

    Thanks, great tutorial!
    Everything is working for me but there’s just one issue.
    The the menu dot appears between the notification and settings menu items for some reason.
    Could someone guide me on correcting this issue?

  • Hossein Amini

    Thank You, for this tutorial.
    This tutorial has a bug that is when we open photos fragment and rotate device to landscape by clicking on home item in navigation drawer, the home fragment will not open. This bug happenes because
    by rotating device CURRENT_TAG value set to TAG_HOME instead of remain TAG_PHOTOS. For fixing this bug i saved CURRENT_TAG value in bundle in onSaveInstanceState method and in onCreate method I retrieved bundle value and set it to CURRENT_TAG.

  • vetri

    Actually the about us page is empty in this tutorial, so how to add some content in About us page??

  • Sagarika Mandal

    Hi.. My app is crashing even before it opens… Help me..

    • Soumyabrata Talapatra

      same here

    • alok singh

      you have to implements HomeFragment.OnFragmentInteractionListener in mainActivity

    • Philips

      In your fragment, try to comment the code inside the void onAttach method ( except “super.onAttach(context);”), it solved the problem for me

  • Soumyabrata Talapatra

    Error:(13, 24) No resource found that matches the given name (at ‘theme’ with value ‘@style/AppTheme.AppBarOverlay’).
    not getting any clue help me

    • vijaya priya

      you need to add

      inside the style xml file

  • hossein

    hi
    how i can change header background?

  • Mohamed Mohy

    thanks great tutorial
    when i change device orientation to landscape the name of menu item list of drawer in toolbar change
    to app name did i miss some thing

  • sirvan alie

    Hi … Thank’s Ravi

    How I can added recyclerView to any of Fragments in this project.

    Please help me ….

    • Mariusz

      Good question!!! I have the same problem 🙂 Please help!

      • sirvan alie

        I solved this Challenge 🙂

  • Howard Park

    great tutorial for using Fragments

  • Jerry Goyal

    @ravi8x:disqus how can I add navigation drawer to existing project. initially i made the app using your cardview app example and now I want to add the navigation drawer to that app. Clearly it’s conflicting and the app is crashing. How to resolve?

    • test

      Check your gradle script. You need to import the appropriate libraries

  • Dheeraj Singh Rathore

    Hello Ravi,
    I am using Navigation Drawer with View Pager but both are overlap to each other. So, I want to say that please let me know one example about this topic.

    Thanks

  • Uday Singh

    hello sir,,, i am new android developer and i want to create a popup window with sliding images…also i want that if i click on first image then first image will comes on the popup and if i click on image 2 or 3 then that image will come up on pop with slider….could you help me in that….

  • Jay Shah

    Error:A problem occurred configuring project ‘:app’.
    > Could not find support-v4.jar (com.android.support:support-v4:24.0.0).
    Searched in the following locations:
    https://jcenter.bintray.com/com/android/support/support-v4/24.0.0/support-v4-24.0.0.jar

    what is solution of this problem???????????????

    • Shomazz

      May be you forgot put in build.gradle those lines ”
      compile ‘com.android.support:appcompat-v7:24.0.0-beta1’
      compile ‘com.android.support:design:24.0.0-beta1’
      compile ‘com.android.support:support-v4:24.0.0-beta1’

  • Mbali

    How can I fix these two errors:

    1) Error:java.io.FileNotFoundException: C:Users…NavigationDrawerNavigationDrawerappbuildintermediatesresmergeddebugdrawable-xxxhdpi-v4abc_ic_star_half_black_16dp.png (The process cannot access the file because it is being used by another process)

    2) Error:Execution failed for task ‘:app:mergeDebugResources’.
    > Error: java.io.FileNotFoundException: C:Users…NavigationDrawerNavigationDrawerappbuildintermediatesresmergeddebugdrawable-xxxhdpi-v4abc_ic_star_half_black_16dp.png (The process cannot access the file because it is being used by another process)

  • Leo Neo

    Thank you so much. It worked for me!! I wish though there was an explanation of what some code does.

    • save Ds

      Dear Leo,

      How did you set those dependencies? Fro me i am getting this error. All dependencies refused to sysnc.

      Error:(10, 0) Could not find method compile() for arguments [directory ‘libs’] on object of type org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler.

      • Leo Neo

        Hello, What I did, I downloaded the project, rebuilt it and then it worked. This project is old so you may just want to Rebuild it

  • Ordint Zeffa Aradhea

    Hi Ravi,
    thank for the tutorial, I got a problem.
    When i try to run the apps, I get this n