You might have heard of android Material Design which was introduced in Android Lollipop version. In Material Design lot of new things were introduced like Material Theme, new widgets, custom shadows, vector drawables and custom animations. If you haven’t working on Material Design yet, this article will give you a good start.

In this tutorial we are going to learn the basic steps of Material Design development i.e writing the custom theme and implementing the navigation drawer using the RecyclerView.

Go through the below links to get more knowledge over Material Design.

> Material Design Specifications

> Creating Apps with Material Design

android getting started with material design

1. Downloading Android Studio

Before going further, download the Android Studio and do the necessary setup as I am going to use Android Studio for all my tutorial from now on. If you are trying the Android Studio for the first time, go the overview doc to get complete overview of android studio.

2. Material Design Color Customization

Material Design provides set of properties to customize the Material Design Color theme. But we use five primary attributes to customize overall theme.

colorPrimaryDark – This is darkest primary color of the app mainly applies to notification bar background.

colorPrimary – This is the primary color of the app. This color will be applied as toolbar background.

textColorPrimary – This is the primary color of text. This applies to toolbar title.

windowBackground – This is the default background color of the app.

navigationBarColor – This color defines the background color of footer navigation bar.

android-material-design-color-schema

You can go through this material design color patterns and choose the one that suits your app.

3. Creating Material Design Theme

1. In Android Studio, go to File ⇒ New Project and fill all the details required to create a new project. When it prompts to select a default activity, select Blank Activity and proceed.

2. Open res ⇒ values ⇒ strings.xml and add below string values.

<resources>
    <string name="app_name">Material Design</string>
    <string name="action_settings">Settings</string>
    <string name="action_search">Search</string>
    <string name="drawer_open">Open</string>
    <string name="drawer_close">Close</string>

    <string name="nav_item_home">Home</string>
    <string name="nav_item_friends">Friends</string>
    <string name="nav_item_notifications">Messages</string>

    <!-- navigation drawer item labels  -->
    <string-array name="nav_drawer_labels">
        <item>@string/nav_item_home</item>
        <item>@string/nav_item_friends</item>
        <item>@string/nav_item_notifications</item>
    </string-array>

    <string name="title_messages">Messages</string>
    <string name="title_friends">Friends</string>
    <string name="title_home">Home</string>
</resources>

3. Open res ⇒ values ⇒ colors.xml and add the below color values. If you don’t find colors.xml, create a new resource file with the name.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#F50057</color>
    <color name="colorPrimaryDark">#C51162</color>
    <color name="textColorPrimary">#FFFFFF</color>
    <color name="windowBackground">#FFFFFF</color>
    <color name="navigationBarColor">#000000</color>
    <color name="colorAccent">#FF80AB</color>
</resources>

4. Open res ⇒ values ⇒ dimens.xml and add below dimensions.

<resources>
    <!-- Default screen margins, per the Android Design guidelines. -->
    <dimen name="activity_horizontal_margin">16dp</dimen>
    <dimen name="activity_vertical_margin">16dp</dimen>
    <dimen name="nav_drawer_width">260dp</dimen>
</resources>

5. Open styles.xml under res ⇒ values and add below styles. The styles defined in this styles.xml are common to all the android versions. Here I am naming my theme as MyMaterialTheme.

<resources>

    <style name="MyMaterialTheme" parent="MyMaterialTheme.Base">

    </style>

    <style name="MyMaterialTheme.Base" parent="Theme.AppCompat.Light.DarkActionBar">
        <item name="windowNoTitle">true</item>
        <item name="windowActionBar">false</item>
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>
    
</resources>

6. Now under res, create a folder named values-v21. Inside values-v21, create another styles.xml with the below styles. These styles are specific to Android Lollipop only.

<resources>

    <style name="MyMaterialTheme" parent="MyMaterialTheme.Base">
        <item name="android:windowContentTransitions">true</item>
        <item name="android:windowAllowEnterTransitionOverlap">true</item>
        <item name="android:windowAllowReturnTransitionOverlap">true</item>
        <item name="android:windowSharedElementEnterTransition">@android:transition/move</item>
        <item name="android:windowSharedElementExitTransition">@android:transition/move</item>
    </style>

</resources>

7. Now we have the basic Material Design styles ready. In order to apply the theme, open AndroidManifest.xml and modify the android:theme attribute of <application> tag.

android:theme="@style/MyMaterialTheme"

So after applying the theme, your AndroidManifest.xml should look like below.

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/MyMaterialTheme" >
        <activity
            android:name=".activity.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

</manifest>

Now if you run the app, you can see the notification bar color changed to the color that we have mentioned in our styles.

android-material-design-notification-bar

3.1 Adding the Toolbar (Action Bar)

Adding the toolbar is very easy. All you have to do is, create a separate layout for the toolbar and include it in other layout wherever you want the toolbar to be displayed.

8. Create an xml file named toolbar.xml under res ⇒ layout and add android.support.v7.widget.Toolbar element. This create the toolbar with specific height and theming.

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:local="http://schemas.android.com/apk/res-auto"
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:minHeight="?attr/actionBarSize"
    android:background="?attr/colorPrimary"
    local:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
    local:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

9. Open the layout file of your main activity (activity_main.xml) and add the toolbar using <include/> tag.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:orientation="vertical">

        <include
            android:id="@+id/toolbar"
            layout="@layout/toolbar" />
    </LinearLayout>


</RelativeLayout>

Run the app and see if the toolbar displayed on the screen or not.

android-material-design-toolbar

Now let’s try to add a toolbar title and enable the action items.

10. Download this search icon and import it into Android Studio as a Image Asset.

11. To import the Image Asset in Android Studio, right click on res ⇒ New ⇒ Image Asset. It will show you a popup window to import the resource. Browse the search icon that you have downloaded in the above step, select Action Bar and Tab Icons for Asset Type and give the resource name as ic_search_action and proceed.

android-studio-importing-image-asset

12. Once the icon is imported, open menu_main.xml located under res ⇒ menu and add the search menu item as mentioned below.

13. Now open your MainActivity.java and do the below changes.

> Extend the activity from AppCompatActivity

> Enable the toolbar by calling setSupportActionBar() by passing the toolbar object.

> Override onCreateOptionsMenu() and onOptionsItemSelected() methods to enable toolbar action items.

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;

public class MainActivity extends AppCompatActivity {

    private Toolbar mToolbar;

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

        mToolbar = (Toolbar) findViewById(R.id.toolbar);

        setSupportActionBar(mToolbar);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, 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_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

After doing the above changes, if you run the app, you should see the search icon and action overflow icon.

android-material-design-toolbar-action-items

3.2 Adding Navigation Drawer

Adding navigation drawer is same as that we do before lollipop, but instead if using ListView for menu items, we use RecyclerView in material design. So let’s see how to implement the navigation drawer with RecyclerView.

14. In your project’s java folder, create three packages named activity, adapter, model and move your MainActivity.java to activity package. This will keep your project organized.

15. Open build.gradle located under your app module and add below dependencies. After adding the dependencies, goto Build ⇒ Rebuild Project to download required libraries.

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

16. Under model package, create a class named NavDrawerItem.java with the below code. This model class is POJO class that defines each row in navigation drawer menu.

17. Under res ⇒ layout, create an xml layout named nav_drawer_row.xml and add the below code. The layout renders each row in navigation drawer menu. If you want to customize the navigation drawer menu item, you have to do the changes in this file. For now it has only one TextView.

18. Download this profile icon and paste it in your drawable folder. This step is optional, but this icon used in the navigation drawer header part.

19. Create another xml layout named fragment_navigation_drawer.xml and add the below code. This layout renders the complete navigation drawer view. This layout contains a header section to display the user information and a RecyclerView to display the list view.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/white">


    <RelativeLayout
        android:id="@+id/nav_header_container"
        android:layout_width="match_parent"
        android:layout_height="140dp"
        android:layout_alignParentTop="true"
        android:background="@color/colorPrimary">

        <ImageView
            android:layout_width="70dp"
            android:layout_height="70dp"
            android:src="@drawable/ic_profile"
            android:scaleType="fitCenter"
            android:layout_centerInParent="true" />

    </RelativeLayout>


    <android.support.v7.widget.RecyclerView
        android:id="@+id/drawerList"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/nav_header_container"
        android:layout_marginTop="15dp" />


</RelativeLayout>

20. As the RecyclerView is customized, we need an adapter class to render the custom xml layout. So under adapter package, create a class named NavigationDrawerAdapter.java and paste the below code. This adapter class inflates nav_drawer_row.xml and renders the RecycleView drawer menu.

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import java.util.Collections;
import java.util.List;

/**
 * Created by Ravi Tamada on 12-03-2015.
 */
public class NavigationDrawerAdapter extends RecyclerView.Adapter<NavigationDrawerAdapter.MyViewHolder> {
    List<NavDrawerItem> data = Collections.emptyList();
    private LayoutInflater inflater;
    private Context context;

    public NavigationDrawerAdapter(Context context, List<NavDrawerItem> data) {
        this.context = context;
        inflater = LayoutInflater.from(context);
        this.data = data;
    }

    public void delete(int position) {
        data.remove(position);
        notifyItemRemoved(position);
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = inflater.inflate(R.layout.nav_drawer_row, parent, false);
        MyViewHolder holder = new MyViewHolder(view);
        return holder;
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        NavDrawerItem current = data.get(position);
        holder.title.setText(current.getTitle());
    }

    @Override
    public int getItemCount() {
        return data.size();
    }

    class MyViewHolder extends RecyclerView.ViewHolder {
        TextView title;

        public MyViewHolder(View itemView) {
            super(itemView);
            title = (TextView) itemView.findViewById(R.id.title);
        }
    }
}

21. Under activity package, create a fragment named FragmentDrawer.java. In Android Studio, to create a new fragment, Right click on activity ⇒ New ⇒ Fragment ⇒ Fragment (Blank) and give your fragment class name.


/**
 * Created by Ravi on 29/07/15.
 */

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;

import java.util.ArrayList;
import java.util.List;

import info.androidhive.materialdesign.R;
import info.androidhive.materialdesign.adapter.NavigationDrawerAdapter;
import info.androidhive.materialdesign.model.NavDrawerItem;

public class FragmentDrawer extends Fragment {

    private static String TAG = FragmentDrawer.class.getSimpleName();

    private RecyclerView recyclerView;
    private ActionBarDrawerToggle mDrawerToggle;
    private DrawerLayout mDrawerLayout;
    private NavigationDrawerAdapter adapter;
    private View containerView;
    private static String[] titles = null;
    private FragmentDrawerListener drawerListener;

    public FragmentDrawer() {

    }

    public void setDrawerListener(FragmentDrawerListener listener) {
        this.drawerListener = listener;
    }

    public static List<NavDrawerItem> getData() {
        List<NavDrawerItem> data = new ArrayList<>();


        // preparing navigation drawer items
        for (int i = 0; i < titles.length; i++) {
            NavDrawerItem navItem = new NavDrawerItem();
            navItem.setTitle(titles[i]);
            data.add(navItem);
        }
        return data;
    }

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

        // drawer labels
        titles = getActivity().getResources().getStringArray(R.array.nav_drawer_labels);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflating view layout
        View layout = inflater.inflate(R.layout.fragment_navigation_drawer, container, false);
        recyclerView = (RecyclerView) layout.findViewById(R.id.drawerList);

        adapter = new NavigationDrawerAdapter(getActivity(), getData());
        recyclerView.setAdapter(adapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getActivity(), recyclerView, new ClickListener() {
            @Override
            public void onClick(View view, int position) {
                drawerListener.onDrawerItemSelected(view, position);
                mDrawerLayout.closeDrawer(containerView);
            }

            @Override
            public void onLongClick(View view, int position) {

            }
        }));

        return layout;
    }


    public void setUp(int fragmentId, DrawerLayout drawerLayout, final Toolbar toolbar) {
        containerView = getActivity().findViewById(fragmentId);
        mDrawerLayout = drawerLayout;
        mDrawerToggle = new ActionBarDrawerToggle(getActivity(), drawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close) {
            @Override
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
                getActivity().invalidateOptionsMenu();
            }

            @Override
            public void onDrawerClosed(View drawerView) {
                super.onDrawerClosed(drawerView);
                getActivity().invalidateOptionsMenu();
            }

            @Override
            public void onDrawerSlide(View drawerView, float slideOffset) {
                super.onDrawerSlide(drawerView, slideOffset);
                toolbar.setAlpha(1 - slideOffset / 2);
            }
        };

        mDrawerLayout.setDrawerListener(mDrawerToggle);
        mDrawerLayout.post(new Runnable() {
            @Override
            public void run() {
                mDrawerToggle.syncState();
            }
        });

    }

    public static interface ClickListener {
        public void onClick(View view, int position);

        public void onLongClick(View view, int position);
    }

    static class RecyclerTouchListener implements RecyclerView.OnItemTouchListener {

        private GestureDetector gestureDetector;
        private ClickListener clickListener;

        public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final ClickListener clickListener) {
            this.clickListener = clickListener;
            gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
                @Override
                public boolean onSingleTapUp(MotionEvent e) {
                    return true;
                }

                @Override
                public void onLongPress(MotionEvent e) {
                    View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
                    if (child != null && clickListener != null) {
                        clickListener.onLongClick(child, recyclerView.getChildPosition(child));
                    }
                }
            });
        }

        @Override
        public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {

            View child = rv.findChildViewUnder(e.getX(), e.getY());
            if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {
                clickListener.onClick(child, rv.getChildPosition(child));
            }
            return false;
        }

        @Override
        public void onTouchEvent(RecyclerView rv, MotionEvent e) {
        }

        @Override
        public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {

        }


    }

    public interface FragmentDrawerListener {
        public void onDrawerItemSelected(View view, int position);
    }
}

22. Finally open main activity layout (activity_main.xml) and modify the layout as below. In this layout we are adding android.support.v4.widget.DrawerLayout to display the navigation drawer menu.

Also you have to give the correct path of your FragmentDrawer in <fragment> element.

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


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

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

            <include
                android:id="@+id/toolbar"
                layout="@layout/toolbar" />
        </LinearLayout>

        <FrameLayout
            android:id="@+id/container_body"
            android:layout_width="fill_parent"
            android:layout_height="0dp"
            android:layout_weight="1" />


    </LinearLayout>


    <fragment
        android:id="@+id/fragment_navigation_drawer"
        android:name="info.androidhive.materialdesign.activity.FragmentDrawer"
        android:layout_width="@dimen/nav_drawer_width"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        app:layout="@layout/fragment_navigation_drawer"
        tools:layout="@layout/fragment_navigation_drawer" />

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

Now we have all the layout files and java classes ready in place. Let’s do the necessary changes in MainActivity to make the navigation drawer functioning.

23. Open your MainActivity.java and do the below changes.

> Implement the activity from FragmentDrawer.FragmentDrawerListener and add the onDrawerItemSelected() override method.

> Create an instance of FragmentDrawer and set the drawer selected listeners.


import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

public class MainActivity extends AppCompatActivity implements FragmentDrawer.FragmentDrawerListener {

    private Toolbar mToolbar;
    private FragmentDrawer drawerFragment;

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

        mToolbar = (Toolbar) findViewById(R.id.toolbar);

        setSupportActionBar(mToolbar);
        getSupportActionBar().setDisplayShowHomeEnabled(true);

        drawerFragment = (FragmentDrawer)
                getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
        drawerFragment.setUp(R.id.fragment_navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout), mToolbar);
        drawerFragment.setDrawerListener(this);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, 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_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onDrawerItemSelected(View view, int position) {

    }
}

Now if you run the app, you can see the navigation drawer with a header and few list items in it.

androd-material-design-navigation-drawer

3.3 Implementing Navigation Drawer Item Selection

Although navigation drawer is functioning, you can see the selection of drawer list items not working. This is because we are yet to implement the click listener on RecyclerView items.

As we have three menu items in navigation drawer (Home, Friends & Messages), we need to create three separate fragment classes for each menu item.

24. Under res layout, create an xml layout named fragment_home.xml and add below code.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="info.androidhive.materialdesign.activity.HomeFragment">


    <TextView
        android:id="@+id/label"
        android:layout_alignParentTop="true"
        android:layout_marginTop="100dp"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:textSize="45dp"
        android:text="HOME"
        android:textStyle="bold"/>

    <TextView
        android:layout_below="@id/label"
        android:layout_centerInParent="true"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textSize="12dp"
        android:layout_marginTop="10dp"
        android:gravity="center_horizontal"
        android:text="Edit fragment_home.xml to change the appearance" />

</RelativeLayout>

25. Under activity package, create a fragment class named HomeFragment.java and add below code.

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


public class HomeFragment extends Fragment {

    public HomeFragment() {
        // Required empty public constructor
    }

    @Override
    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_home, container, false);


        // Inflate the layout for this fragment
        return rootView;
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
    }

    @Override
    public void onDetach() {
        super.onDetach();
    }
}

26. Create two more fragment classes named FriendsFragment.java, MessagesFragment.java and respected layout files named fragment_friends.xml and fragment_messages.xml and add the code from above two steps.

27. Now open MainActivity.java and do the below changes. In the below code

> displayView() method displays the fragment view respected the navigation menu item selection. This method should be called in onDrawerItemSelected() to render the respected view when a navigation menu item is selected.

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity implements FragmentDrawer.FragmentDrawerListener {

    private static String TAG = MainActivity.class.getSimpleName();

    private Toolbar mToolbar;
    private FragmentDrawer drawerFragment;

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

        mToolbar = (Toolbar) findViewById(R.id.toolbar);

        setSupportActionBar(mToolbar);
        getSupportActionBar().setDisplayShowHomeEnabled(true);

        drawerFragment = (FragmentDrawer)
                getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
        drawerFragment.setUp(R.id.fragment_navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout), mToolbar);
        drawerFragment.setDrawerListener(this);

        // display the first navigation drawer view on app launch
        displayView(0);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, 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_settings) {
            return true;
        }

        if(id == R.id.action_search){
            Toast.makeText(getApplicationContext(), "Search action is selected!", Toast.LENGTH_SHORT).show();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onDrawerItemSelected(View view, int position) {
            displayView(position);
    }

    private void displayView(int position) {
        Fragment fragment = null;
        String title = getString(R.string.app_name);
        switch (position) {
            case 0:
                fragment = new HomeFragment();
                title = getString(R.string.title_home);
                break;
            case 1:
                fragment = new FriendsFragment();
                title = getString(R.string.title_friends);
                break;
            case 2:
                fragment = new MessagesFragment();
                title = getString(R.string.title_messages);
                break;
            default:
                break;
        }

        if (fragment != null) {
            FragmentManager fragmentManager = getSupportFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            fragmentTransaction.replace(R.id.container_body, fragment);
            fragmentTransaction.commit();

            // set the toolbar title
            getSupportActionBar().setTitle(title);
        }
    }
}

Now if you run the app, you can see the selection of navigation drawer menu is working and respected view displayed below the toolbar.

android-material-design-navigation-drawer-1
android-material-design-navigation-drawer-2
android-material-design-navigation-drawer-3

What’s Next?

Below are few more material components you can add to your app. These were implemented using recent Android Design Support Library.

1. Sliding Menu using Navigation Drawer

The Navigation Drawer is added using Navigation View and Drawer Layout.

2. Material Design Tab Layout

If you want to add tabs to your app, Android Material Design Tabs covers different aspects of Tab Layout.

3. Floating Labels for EditText

Learn how floating labels works on EditText with a simple form validation example.

4. Floating Action Button (FAB)

Add the Floating Action Button to your which displays in circular shape floating on the top of the UI.

5. Snackbar

Add the Snackbar to your app to give immediate feedback about any operation that user performed.

Change Log

Updated On 29th July 2015 (Latest support library)
19th Sep 2016 (Bug fixes and content update)
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.
  • sunil sarode

    Thanks lot , your tutorials i love it ……..:)

  • Basil Alias

    Thanks..

  • Josh Holiday

    Thank you a lot! Been waiting for that tutorial for a long time!

  • Oyewole Samuel Success

    I’ve been waiting for this tuts, Please how can i add shadow to that toolbar? Thanks

    • Use android:elevation=”2dp” to toolbar.

      • Terry

        on the android connecting to mysql what can l do to make it work on my phone? thanks in advance

  • Adel Jaffan

    amazing 🙂

  • Nice !! I would like to see a post on Material Design Animations from Android Hive !!

  • Devrath Dev

    Thanks Ravi …. I also did drop this Exact Tutorial request in your Facebook msgs … Very nice tutorial man … Cheers !

  • Siranjeevi

    Thanks Ravi… Kindly Share lot of concepts with Android 5.0 API’s. Also Share How to work android studio as effective.

  • Niranga Sandaruwan

    great post Ravi…i am developing android apps using eclipse as IDE.How do i support my material design app which is developed in eclipse for pre lollipop device.in eclipse there is no gradle.where should i put
    compile ‘com.android.support:appcompat-v7:22.0.0’

    compile ‘com.android.support:recyclerview-v7:21.0.+’

    these two dependency in eclipse.

  • Dawkin’s Kamara

    Thanks Ravi!

  • Alaa Hossam

    Awesome,Thank you Ravi!

  • Ahmed

    How i set icon for item drawer ?

  • Trey Rosius

    U make android programming look too easy…thanks for keeping it simple.You are a true GURU..thank you

  • Anoop

    @Ravi Tamada You can inflate the actionbar menu using mToolbar.inflateMenu(menuResId). This is the more recommended way to do it.

  • kristich

    the problem is you need to understand fragment to use this tut…… and using fragment with REST api or REST services is some anoying problem……

    • Can you explain me whats the problem we get when using Fragment?

  • Utpal Ruparel

    I am using your tutorial since first day I started Android. Can you please tell me Will API 10-11 support Material Design?

    • No they won’t support. The things like animations, ripple effects and few other things won’t work. But you will get the uniform look across all the android versions.

  • Francisco

    thank you so much… it really help me….. Gracias.

  • John

    How can you implement back button action to this drawer (history when changing between fragments) ?

    • Arjun Bansil

      Add each fragment to the backstack trace. It’s not elegant but it works.

      • John

        Can you give me an example ?

  • angra89

    Great tutorial!! keep doing it.

  • manvi

    hello ….. its so awesome tutorial .. just need to know that can i use this whole code with eclipse …???

    • alekdi

      Just follow the tutorial as is, instead to use Gradle, you have to manually import the jar of app compact in your lib folder, and add it as a library in your project structure.

      • manvi

        thank you so much dear for ur rply …… can u just tell me which jar files i have to import nd how i have to work for it …… thank u so much in advance ..

        • Alekdi

          Sorry for the reply. In eclipse you have to do this steps:

          – manually copy/paste compatibility-v7-appcompat-22.0.0-sources.jar (google it to find the jar)

          – Right click on the jar you want to add.
          – Build Path > Add to Build Path

          Done.
          Here the official documentation: https://developer.android.com/tools/support-library/setup.html

  • ali hussnain

    you are awesome man,you made my life much easier so far, in android development 🙂

  • vikrant

    does this work on 4.4.2

    • Alekdi

      Yes it does.

  • So finally you migrated to Android Studio. 🙂

  • Pramoda

    usefull and good work brother thanks…

  • Abhimanyu R Shrivastava

    Great tutorial………I have a question,
    How I can update the selection of drawer items to notify which row is currently selected?

  • Urnish Makwana

    First of all thanks for nice and easy tutorial..
    My question is, Suppose when i click on “Home fragment”, a new page will be open as in this application “fragment_home”, suppose their is button in “fragment_home” and i want to navigate it to other page, then how can i implement it.?.. the toolbar must be present in that page also means in fragment / activity.

  • vikrant

    how to replace navigation drawer with back button? in new activity clicked from fragment_home

    • Alekdi

      You have to specify the new activity in the Manifest, with parent your main activity.

  • Bima Aditama

    Material design support Eclipse???

    • Yes, it supports.

      • Bima Aditama

        Can you make a tutorial…

        • Lubulwa Ric

          You can use this same tutorial in eclipse, am using app compact and it is working fine

  • WaWaToR

    Thank you for this great tutorial. Just one little question how and where can i add divider in the navigation drawer?

  • Gheorghita Paul

    Thanks for the tutorial but i seem to have a problem. I am new to Android and when i try to run the app i get 3 errors “cannot resolv symbol” in MainActivity.java

    private void displayView(int position) {

    Fragment fragment = null;

    String title = getString(R.string.app_name);

    switch (position) {

    case 0:

    fragment = new HomeFragment(); //Error here with cannot resolve symbol

    title = getString(R.string.title_home);

    break;

    case 1:

    fragment = new FriendsFragment(); //Error here with cannot resolve symbol

    title = getString(R.string.title_friends);

    break;

    case 2:

    fragment = new MessagesFragment(); //Error here with cannot resolve symbol

    title = getString(R.string.title_messages);

    break;

    default:

    break;

    }

    Any help with that? 😀

    • Renitto Jose

      Great Work Ravi . We are Going to Switch to Android Studio and Material from next Project onwards and Hope Your Tutorials will help alot 🙂 . Keep Up the good work (y)

  • Kim Dotnet

    Great tutorial like always. I have a question do you think RetroFIt is better than “Volley” Library?

  • Yadnyesh

    Great tutorial..Can you post tutorial on swipable tabs with material designs? Thanks in advance!!

  • How to make the sidebar appear under the system toolbar (not the navbar at the bottom)?

  • Viraj

    is this specific to lollipop ? because notification bar color is not changing in below lollipop.

    • James Seddon

      You can’t change the status bar colour in pre-lollipop, although you can add a graduated colour.

  • Arjun

    How do i add third party libraries to my porject through Android Studio ?

    • alekdi

      In your build.gradle file in the app folder, add in the dependencies the library you want to add using “compile ‘your_library'” and sync project.

      Another method is to add the jar in the libs folder of your project, right click on it and choose “add as library”, rebuild project and done.

      • Arjun

        Didn’t get you mate , Please be clear. Thank you

        • alekdi

          Sorry for the late.

          Follow this steps in order:

          1- copy your .jar file in the libs folder of the project, if there isn’t the folder create it.

          2- right click on it, click on “Add as Library”

          3- Sync your gradle project

          If all steps are done good, you should see something like this in the dependencies of your build.gradle file in app folder:

          dependencies {

          compile fileTree(dir: ‘libs’, include: [‘*.jar’])

          compile files(‘libs/YOUR_JAR.jar’)

          }

          /************/

          Another method (the simpler) is to add this line in the build.gradle of /app/ folder in your project:

          dependencies {

          compile ‘com.YOUR_LIBRARY’

          }

          Example: if you want to add the app-compat v7, you should add:

          compile ‘com.android.support:appcompat-v7:22.0.0’ in your build.gradle

          After that, Sync the project and all is done.

          Hope that helps

          Alekdi

          • Arjun

            Thanks a ton, Alekdi

        • alekdi

          Read the official documentation, is really simple: https://developer.android.com/tools/support-library/setup.html

  • Jack Teh

    can u come out a guide with adding lollipop ripple effect on selection~

    • @rpit Patel

      this is temporary solution to add this into your gradle file

      compile ‘com.github.traex.rippleeffect:library:1.3’

      And put like this

  • Maik Braga

    Muito bom seu artigo. Parabéns!

  • Rygel

    You are my hero Ravi! i was watting for this tutorial for so long, you just saved my week bro. Thank you man!
    And finally you have switched to Android Studio 😉

  • Christian Moscosa

    Great tutorial! May I ask if how many fragment that I can add on the drawer? thanks! Appreciate it,

    • Christian Moscosa

      Already got it, I forgot to put nav_drawer_labels under strings.xml. Thanks bro!

  • Anggrayudi H

    Hi Ravi, what about activatedBackgroundIndicator attribute for that Navigation Drawer? Can you add one step for this?

  • Kurt Marko

    Does it work on android older then lolipop. Thanks

    • Salar Rastari

      no i don’t think so.
      i tested on android 4+ and it doesn’t work.

    • Munim

      Its working for me on Android 4.2.2 API Level 19

      • Siya

        Hey did you write separate code for lower versions?

        • Munim

          Nope. Current code works as it is.

  • When I run the Application before Adding the Toolbar (Action Bar) I get this error :-

    Caused by: java.lang.IllegalArgumentException: AppCompat does not support the current theme features

    at android.support.v7.app.AppCompatDelegateImplV7.ensureSubDecor(AppCompatDelegateImplV7.java:360)

    at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:246)

    at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:106)

    at ……………….. .MainActivity.onCreate(MainActivity.java:14)

    It works fine after changing parent=”Theme.AppCompat.Light.DarkActionBar”
    to
    parent=”Theme.AppCompat.NoActionBar”

    • jatin

      Add true in styles.xml

      • This line is already there.
        It works fine after changing parent=”Theme.AppCompat.Light.DarkActionBar”
        to
        parent=”Theme.AppCompat.NoActionBar”

        • Mergim Krasniqi

          Joginder Sharma – Insert in styles.xml

          true

          • What works for me is: “Theme.Appcompat.Light.NoActionBar”
            Also for your Toolbar, change the change app:theme to android:theme
            Should work fine

          • @suleiman19:disqus can you create new activities and have the same actionbar displayed?

          • The ‘Toolbar’ works like any other view, so you must include it in all activities where you which to have an ActionBar. Simply include the same Toolbar in those activities.
            Remember ‘setSupportActionBar(mToolbar);’ is the key to make your Toolbar behave as an ActionBar 🙂

  • Salar Rastari

    Hi Ravi, thank you so much
    would you please give me more details how to add Icons for nav items?
    i couldn’t get help from this tutorial http://www.androidhive.info/2013/11/android-sliding-menu-using-navigation-drawer/
    and would you please learn us how to add swipe tabs in one of the nav items? also this tutorial http://www.androidhive.info/2013/10/android-tab-layout-with-swipeable-views-1/ doesn’t help me

  • Sina Riani

    Hi Ravi, thanks for your great tutorials
    I have a problem in putting icons for navigation Drawer elements , how can i do that?
    Next…please put a tutorial about how to create swipe tab in a navigation Drawer menu?
    thanks a lot

  • kiran

    Hello Ravi, ur tutorial works fine for me one small favour for me is how to have back navigaion in the action bar in this tutorial such as i have another activity and when back navigation in action bar is pressed it should go back to home

  • Dmitriy Dzyuba

    Thanks Ravi! But I have a trouble… I want ….
    startActivity(new Intent(MainActivity.this, Save.class));


    public class Save extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_save);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }
    }

    But I have crash when I want show ActionBar with back navigation. getSupportActionBar().setDisplayHomeAsUpEnabled(true); – null pointer
    I searched but did not find the possibility to solve my problem.

    Thanks for help!

    • alekdi

      Did you add the activity in your Manifest with parent the Main activity? in the OnCreate method you forgot to add
      getSupportActionBar().setHomeButtonEnabled(true );

      • Dmitriy Dzyuba

        Solved the problem, need to add in onCreate. Thanks

        Toolbar mToolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(mToolbar);

  • MD Danish Ansari

    how do i make the navigation drawer below the toolbar so that i see the toolbar even when the drawer is pulled ?????

  • Arjun

    Can anyone please tell me What are the free libraries that any android developers can use ? and what is an adapter and handlers in android and what are they use for, I was asked this questions in an interview but couldn’t answer this as i am new to android. Please help.Thank you

  • Daniel Contreras

    great tutorial, but, How can i add functionality to the layout? , I tried but does nothing, in the layoult of home I put buttons that when pressed show text, but simply does nothing. Help me please

  • Salar Rastari

    Hi Ravi, please help us how to add icons?
    if u can’t answer please say.
    thank you.

  • hamid

    hi rawi !
    how set toolbar open from right to left ?

    • Ziz

      1) Add in your Android Manifest below “<application …"

      android:supportsRtl="true"

      2 ) then Add this in your "onCreate" in MainActivity

      // View Right to Left

      if (getWindow().getDecorView().getLayoutDirection() == View.LAYOUT_DIRECTION_LTR){

      getWindow().getDecorView().setLayoutDirection(View.LAYOUT_DIRECTION_RTL);

      }

      This should put all the content from left to right

  • Awesome Rabi. Thanks so much!

  • Arjun

    When to use fragments over activity ? Please help

  • Ziz

    Hi , thank you for this tutorial , very useful !

    I could use some help, I have this error :”Didn’t find class “android.view.android” ”

    It comes from the “<android.support.v4.widget.DrawerLayout" in the activity_main.xml

    I've added "compile 'com.android.support:support-v4:21.0.3'" in the build.gradle but it changed nothing.

    Any clue?

  • Hi Ravi,
    Thanks for keeping my request on Android Material Design……

  • Septian Yudha

    Hi Ravi, after long waiting finally you get into Android Studio and Material Design world.
    Thanks so much. 🙂

  • rami

    very nice

  • sankar

    nice work…..

  • Arun Pandiyan

    I need to add icon near the navigation drawer items. Any suggestions

  • Julian Reyes E

    I found this tutorial pretty useful, But I have a doubt, How I can enable/disable the drawer

  • Nasif Ahmed

    First thanks @ravi8x:disqus for continuing your great tutorial. Now I have two question-
    1.Why we use app compact v7 support lib and support fragment here? Isn’t material design possible without these support library for 15+ version?
    2.Why we extend ActionBarActiviy?

  • nomas

    Hello Ravi! Great tutorial! Really good job. I just wanted to ask a very simple question since I am newbie and I am trying to learn android programming from your tutorials. Why when I change orientation of my phone I keep going to the Home Fragment instead of remaining on the Fragment I have selected from the navigation drawer? What do you propose in order to do so? Many thanks in advance!

    • Michal

      When you change orientation of your phone, the activity is not just “rotated”, but recreated. It means, that it’s destroyed and onCreate method is called. Your activity is brand new, with it’s default look, hence the first fragment, I assume. Try to use savedInstanceState parameter of onCreate to store and retrieve the UI state – the current fragment index, in your case.

      http://developer.android.com/training/basics/activity-lifecycle/recreating.html

  • Sơn Đinh

    I want change ic_profile in Onclick event, how I will perform

  • Anto

    Hello Ravi.
    what’s the example project only in Android Studio?
    I’m try in ADT it’s not working. are you have example project with ADT?
    Location error in file styles.xml about

    true
    false
    @color/colorPrimary
    @color/colorPrimaryDark
    @color/colorAccent
    @color/textColorPrimary
    @color/windowBackground

    thanks

    • Hi, I could give it a shot if you told which version of AppCompat you’re using.

  • Vipul patel

    Hello Ravi…
    You are best descriptor of all android examples till date..

    thanx for such a lovely guidance..

    i am having a question.. it would be very grateful if u help me out with that.. Is there any way by which we can transform our default design into material design directly by some sort of codes..?
    is there any such api or libraries for that..?

  • Anil

    Hello Ravi,

    i am facing a problem with this code. when i complie the code its giving me error.

    Error: cannot find symbol method setSupportActionBar(Toolbar). i surf on google everybody says use ActionBarActivity instead of Activity but i already use ActionBarActivity. But its giving me the same error

    • Nguyễn Đức Huy

      I am also have problem like you

      • Anil

        Hi Nguyen,

        I solved this problem. In my application i found a old appcompact library in my lib folder. after delete that library its working fine,

  • Meyka Jograt

    Hello Ravi,

    why ActionBarActivity is deprecated in Main activity? how can i fix this? someone know it ? help me please ~

    • Aleksander Larionov

      Use AppCompatActivity instead ActionBarActivity

      • Meyka Jograt

        yes i did that :3

        • Yes, that’s the solution. It’s changed ever since AppCompat v22.1.1

  • karampal

    hiii please help me to solve the following error:-
    java.lang.IllegalArgumentException: AppCompat does not support the current theme features

    • Hillel SAAL

      Just change theme

      • karampal

        No this is not a problem due theme
        When i use target SDK 21 it will run but when i change it ti target SDK 22 it goes force close and says
        Above error…

        • HK

          have you sepcified your theme in the values – > styles file or some values-v[x] -> styles file

          • karampal

            Yes…

          • HK

            which theme r u extending from. Try extending the Theme.AppCompat.NoActionBar

          • HK

            OR may be use this in ur style,

            false
            true

          • karampal

            thanks for help…

    • Mayur

      just add this:

      tools:replace=”android:icon,android:theme,android:label”

      in your AndroidManifest.xml file of your main application under ……..tools:replace label…..

      It will get build successfully.

      • karampal

        thanks for help…I will try this later but now help me for tab view in fragments

  • Ari

    Hi, how can I add icons in the navigation drawer?

    • Same question. Thanks before

    • ammy

      drawerFragment.setUp(R.id.your icon_name, (DrawerLayout) findViewById(R.id.drawer_layout), mToolbar);try here to add icon

  • karampal

    I want to use tab view in fragments of this navigation drawer can any one help me how use swipe-able tab view in fragment……?

  • Alageson Ravi

    Nice tutorial and it is very useful. But after finishing every think it gives an error that it could not find the Main Activity file compiler gives information that activity file is missing because we have shifted to activity folder. Then how to correct it. email: ravi_abm@yahoo.co.in

  • Alageson Ravi

    cat. error details——
    java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{techno.com.goldendesign/techno.com.goldendesign.MainActivity}: java.lang.ClassNotFoundException: Didn’t find class “techno.com.goldendesign.MainActivity” on

  • Vikrant Bhave

    How to change icon colors from white to e.g. green or blue

  • usarrr

    why while on the run in android apps straight out ?

  • Alageson Ravi

    Pl I have tried several time it is not working. It gives the following error code

    Starting: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] cmp=techno.com.hivemateial/activity.MainActivity }
    Error type 3
    Error: Activity class {techno.com.hivemateial/activity.MainActivity} does not exist.
    (ravi_abm@yahoo.co.in)

  • Amit Kumar Verma

    Hi Ravi,how can open child fragment from home fragment with back button on action bar

    • Alageson Ravi

      Thanks corrected and is working

  • Ashik Rahman

    When i run the app it goes straight away getting this logcat error.

    Unable to start activity ComponentInfo{com.rahman.ashik.material/com.rahman.ashik.material.MainActivity}: java.lang.IllegalArgumentException: AppCompat does not support the current theme features

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

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

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

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

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

    at android.os.Looper.loop(Looper.java:211)
    ………..
    and so on……

    Note that my target sdk version 21 and build version 21 in sdk 16

    • Change Theme.AppCompat.Light.DarkActionBar to just Theme.AppCompact

  • maxxanh

    Ravi hello, I have a little trouble when i clicking the menu icon is not displayed menu

    Here is the source code

    MainActivity.java

    drawerFragment = (FragmentDrawer)
    getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
    drawerFragment.setUp(R.id.fragment_navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout));
    drawerFragment.setDrawerListener(this);

    FragmentDrawer.java

    public void setUp(int fragmentId, DrawerLayout drawerLayout) {
    containerView = getActivity().findViewById(fragmentId);
    mDrawerLayout = drawerLayout;
    mDrawerToggle = new ActionBarDrawerToggle(getActivity(), mDrawerLayout, R.string.drawer_open, R.string.drawer_close) {
    @Override
    public void onDrawerOpened(View drawerView) {
    super.onDrawerOpened(drawerView);
    getActivity().invalidateOptionsMenu();
    }

    @Override
    public void onDrawerClosed(View drawerView) {
    super.onDrawerClosed(drawerView);
    getActivity().invalidateOptionsMenu();
    }

    @Override
    public void onDrawerSlide(View drawerView, float slideOffset) {
    super.onDrawerSlide(drawerView, slideOffset);

    }
    };

    mDrawerLayout.setDrawerListener(mDrawerToggle);
    mDrawerLayout.post(new Runnable() {
    @Override
    public void run() {
    mDrawerToggle.syncState();
    }
    });
    }

  • Max xanh

    Ravi hello, I have a little trouble when i clicking the menu icon is not displayed menu

    Here is the source code

    MainActivity.java

    drawerFragment = (FragmentDrawer)
    getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
    drawerFragment.setUp(R.id.fragment_navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout));
    drawerFragment.setDrawerListener(this);

    FragmentDrawer.java

    public void setUp(int fragmentId, DrawerLayout drawerLayout) {
    containerView = getActivity().findViewById(fragmentId);
    mDrawerLayout = drawerLayout;
    mDrawerToggle = new ActionBarDrawerToggle(getActivity(), mDrawerLayout, R.string.drawer_open, R.string.drawer_close) {
    @Override
    public void onDrawerOpened(View drawerView) {
    super.onDrawerOpened(drawerView);
    getActivity().invalidateOptionsMenu();
    }

    @Override
    public void onDrawerClosed(View drawerView) {
    super.onDrawerClosed(drawerView);
    getActivity().invalidateOptionsMenu();
    }

    @Override
    public void onDrawerSlide(View drawerView, float slideOffset) {
    super.onDrawerSlide(drawerView, slideOffset);

    }
    };

    mDrawerLayout.setDrawerListener(mDrawerToggle);
    mDrawerLayout.post(new Runnable() {
    @Override
    public void run() {
    mDrawerToggle.syncState();
    }
    });
    }

  • Paolo Gentile

    Hi, i’ve extended this project creating new activities. How can i get on the other activities that ripple effect when you press on search icon? Thank you guys!

    • Is the actionbar displayed on new activites? can you post the code?

  • Udo M.

    Hi, thank you very much for this tutorial. It really helps me to get material design within my app. I am just stuck in one step, when implementing the navigation drawer in the MainActivity.java:

    drawerFragment = (FragmentDrawer) getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
    It says, I cannot cast ‘android.support.v4.app.Fragment’ to ‘my.package.name.
    .activity.FragmentDrawer’ Can you help me? Thank you very much in advance!

    • Udo M.

      Nevermind, problem soved:
      Just go to your Fragment_navigation class and
      replace “import android.app.Fragment;” with “import android.support.v4.app.Fragment;”

    • shubha

      replace getSupportFragmentManager() with getFragmentManager()
      in my case this was the solution

  • Rajinder Kumar

    Awesome tutorial. worked for me. Although there were couple of smalls tweeks you might have to make. One is that comment out the setSupportActionBar(mToolbar) line if you already made a navbar

    • Kiss Anna

      Can you write, what other things did you change to work? When I click on Home or the others, onClick wont be called, it just close the Drawer.

  • Xerib

    Amazing work ! Thank you 🙂

  • Bhavik Shah

    hello,

    i am getting error at

    public static List getData() {
    List data = new ArrayList();

    ERROR: Error:(45, 50) illegal start of type

    • aya zaki

      convert compiler to 1.7

      • Bhavik Shah

        FAILURE: Build failed with an exception.

        * What went wrong:

        Execution failed for task ‘:app:compileDebugJava’.

        > Compilation failed; see the compiler error output for details.

        I changed the compiler still i m getting this error

        • aya zaki

          when i convert compiler to 1.7 it’s work

          try this List data = new ArrayList();

          • Bhavik Shah

            Error:(71, 21) setAdapter(android.support.v7.widget.RecyclerView.Adapter) in android.support.v7.widget.RecyclerView cannot be applied to (want2learn.com.want2learn.adapter.NavigationDrawerAdapter)

            Error:(53, 5) cannot access android.support.v4.view.ScrollingView

            class file for android.support.v4.view.ScrollingView not found

            Error:(19, 8) cannot access android.support.v4.view.NestedScrollingChild

            class file for android.support.v4.view.NestedScrollingChild not found

            Now This 3 Error are coming

            I have just copy pasted the whole code as given by ravi

          • aya zaki

            get android-support-v7-recyclerview.jar
            from sdkextrasandroidsupportv7recyclerviewlibs

            and add it in libs in the project
            then right click on proj->properities->add external lib->pointer to project libs jar that you added

  • Hello,
    Please add the code to expand Search bar on the header
    Thankyou

  • Thusee

    Nice tutorials to learn

    how to do the color change in navigation drawer item clicks ?

  • Ritesh

    Hi nice tutorial you saved my day.. and can we use Dashboard buttons in the main screen using fragments??

  • Snehil

    I have done as it is till step 9 . And I am getting following exception.
    java.lang.UnsupportedOperationException: Can’t convert to color: type=0x1
    How to fix this..

    • Snehil

      done no exception…Actually i was wrong i have edited mainactivity.java do no edit that , here we will change that file on step13.

  • aya zaki

    hello

    i tried this tutorial in eclipse not android studio ,run apk in samsong galaxy s3 i have no toolbar and the

    black below bar i don’t understand why?

  • Jesus Gabriel

    Hi,
    This is one of the bes tutorial I found for sliding menu.
    I have a quick question.
    How do I add the a divider for the menu and a highlight action when a item is pressed?
    Do i Have to add a Listview to accomplish this?

  • Roshan W

    After Little Customization The Code is working ! But Problem is “It doesn’t display Navigation Drawer Item Name & Corresponding Fragment Details”

    Please Check This Link: http://gfycat.com/BreakableSelfreliantHydra

    • fluktuid

      add ‘android:textColor=”attr/colorPrimaryDark’ to the textView in ‘nav_drawer_row.xml’

  • Alfonso Vargas

    Hello Ravi, I have a exception in this line
    setSupportActionBar(mToolbar);
    please, help me.

  • This is working perfectly well. Great tutorial, but the problem lies when you try to create new fragments or activities, the toolbar goes missing. How to get reference to the old toolbar?.
    Also up caret doesn’t work well with lower fragments.

    Please do reply if someone as created new activity and have the same actionbar displayed.

  • Istiyak ahmed

    My gradle build successfully but when I run the app it just stopped. Note that, my android.support.v7.ActionBarActivity is deprecated. Is that the problem , how can I fix it. If some one have the code please give me a link to download, I request for subscribe but get no reply yet.

    • Meyka Jograt

      try to use AppCompat activty 😀 search it for more info ir simple click the AppTheme in your platform then click material dark or light. not so sure if this helps but at least give it a try 😀

      • Istiyak ahmed

        thanks for your reply. It already worked with deprecated android.support.v7.ActionBarActivity. Now I need to add list view in Fragment Drawer.

  • marcoopsone

    Hi, how do I add a button listener ?

    Regards Marco

  • analaurapy

    Thanks Ravi!! This is one of the best tutorial I found!!

  • Ganendra Afrasya

    Kinda all-in-one tutorial……nice !

  • LAY Leangsros

    Thanks!
    But I can’t see item in list(Home,Friends, Messages).

    • Kiss Anna

      If you changed in styles.xml parent to Theme.AppCompat.NoActionBar because of another problem, you should use Theme.AppCompat.Light.NoActionBar instead. It was the issue, I had 🙂

  • dharti pitroda

    How can i Implement navigation drawer as dynamic navigation drawer???

  • شبير البلوشي

    Thank you so much for such an amazing tutorial.. as always it works like a charm. but i have a question.. how to work with profile picture. how user will able to click on profile icon and choose pic for gallery to set as profile picture… plz share .. if any1 else have any idea about it so please share. thanks

  • Mahesh Mahi

    Hi, How can show transparent navigation drawer over status bar

  • sanket patel

    thank you sir..Sir i can change colour of navigation item onitemclick?

  • Sundar

    This is the error i am getting after importing the application..Can u pls hlp to resolve this?? Thanks in advance

    Error:(17, 1) A problem occurred evaluating project ‘:app’.

    > Could not find property ‘MATERIAL_KEYSTORE_FILE’ on SigningConfig_Decorated{name=release, storeFile=null, storePassword=null, keyAlias=null, keyPassword=null, storeType=null}.

  • Khaled Rostampour

    I wanna extend my MainActivity from ListActivity and ActionBarActivity.
    but it’s impossible to do that.
    how can I use both of them in on activity, notice that I’m not using fragment?

  • Koen

    For anyone running into the following error:
    java.lang.IllegalArgumentException: AppCompat does not support the current theme features

    Try changing the following line in styles.xml from:
    true
    to
    true

    That line seemed to give some trouble on API v22.

    • Thanks Koen 🙂

      • Koen

        NP. Great all including tutorial!

  • Kiss Anna

    Heyy, great tutorial! I changed to ….Light.NoActionbar, but when I click on Home/Friends/Messeges, onClick wont be called, it just closes the Drawer. Can anyone help, please?

  • vishal

    Very Good Tutorial Thanks …:)

  • adaivanoff

    This is an awesome tutorial! It’s the best one on MD I’ve seen. Congrats! Keep the good work!

  • Michael

    Really great tutorial, thank you so much Ravi. Just one little issue sometime my app freezers, upon opening/closing the navigation draw. Any idea why this can be? Only change i made, was to extend from AppCompatActivity.

  • Manny264

    After point number 7 I ran the app and it crashed on all platforms.
    This solution asks you to make changes in your default styles.xml and then it runs: http://stackoverflow.com/questions/29784124/java-lang-illegalargumentexception-appcompat-does-not-support-the-current-theme

    • Yes, updated the article.

      • Manny264

        Nice…bless u4these tutorials man

  • John Nicole Dagamat

    HELP.
    “Unfortunately, material design has stopped.”

    **material design is my project name

    • Koen

      Can you explain your problem please. Which step gives you this problem? What piece of code?

      • John Nicole Dagamat

        Well it works now 🙂 I just forgot to edit some codes -_-
        By the way thanks for the fast response 🙂

  • Sabahat Sana

    My error:

    Binary XML line #21 : error inflating class android.support.v7.widget.RecyclerView

    Please help me.

  • Francisco Lima

    Great tutorial, thanks!

  • Krishna Chandramouli

    awesome tutorial, thanks a ton!!! a small clarification,

    1. In the FragmentDrawer.java – recyclerView.getChildPosition(child)) – is referred to as “deprecated”.. any comments on what would be suitable to replace the code with?

  • 盧冠宇

    if I want to use icon in title left,what should I to do ?

  • Sohail Pathan

    Hey @ravi8x:disqus, Thanks man for such a great tutorial…. It was very helpful indeed… I would trouble you little more by asking how do I show Icons for each row i.e. each drawer item… I added a icon in “nav_drawer_row.xml” and also followed your tutorial @ “http://www.androidhive.info/2013/11/android-sliding-menu-using-navigation-drawer/” but couldn’t do it successfully… Damn stuck since yesterday… Please help…

    • Please paste your nav_drawer_row.xml code here.

      • Sohail Pathan
        • Use this code. You have to add
          android:layout_toRightOf=”@id/icon” to your TextView so that it aligns right to icon.

          • Sohail Pathan

            Thanks! but how do I set Icons dynamically like we have set the title in #ref point 20 of this tutorial -> file “NavigationDrawerAdapter” using holder.title.setText(current.getTitle());

          • Sohail Pathan

            Hey @ravi8x:disqus, I’m still trying to figure it out… Please help me out if you can… Thanks in advance…

  • subhasree biswas

    Thanks for this awesome tutorial..it’s running successfully..please tell
    me one more thing..How can I create a drawer of Navigation drawer??I
    mean to say that when click on navigation drawer’s any option,one new
    drawer comes out from it..can you please help me to do this??

  • Nourhenne Sahli

    Hey Ravi Tamada, Thanks for such a great tutorial it helped me so much but i have a question how to add icons to the navigation drawer items plz

  • Rishabh Banga

    FATAL EXCEPTION: main

    08-04 23:36:31.624: E/AndroidRuntime(23316): Process: com.rbrc.findit, PID: 23316

    08-04 23:36:31.624: E/AndroidRuntime(23316): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.rbrc.findit/com.rbrc.findit.activity.MainActivity}: android.view.InflateException: Binary XML file line #16: Error inflating class android.support.v7.widget.RecyclerView

    08-04 23:36:31.624: E/AndroidRuntime(23316): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)

    08-04 23:36:31.624: E/AndroidRuntime(23316): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)

    Getting this error. I’m using Eclipse on SDK Tools, Revision 24. Even in the Graphical layout of activity_main it show this error:

    The following classes could not be instantiated:

    – android.support.v7.widget.RecyclerView (Open Class, Show Error Log)

    • Why are you still using Eclipse? Google already stopped supporting it.

      • Rishabh Banga

        Thanks! Downloaded Android Studio. It already had a more better built in layout and code of what you wrote. Saved a lot of time!

  • Rishabh Banga
  • Bhavik Shah

    drawerFragment = (FragmentDrawer)getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);

    Showing Error on the above line as “Inconvertible types;cannot cast android.support.v4.app.Fragment” to “activity.FragmentDrawer”

    • Patrick J

      I’m getting the same error. Not sure what’s wrong… Anyone know?

    • Deni Șumai

      I found the answer to that. Make sure that the FragmentDrawer class extends android.support.v4.app.Fragment instead of simply Fragment. It solved my problem. 🙂

  • Ravindu

    It was great tuto bro.. many thanks

  • Muhammad Qasim

    Can You please made a complete tutorial on search view using v7.

    1- search view expand
    2- search view contract
    3- search functionality- searching from recycler view

    I really need it, Please help.

    • Giuseppe

      hello, did you find then? I need it too…

  • Great job man!!!! I appreciate so much!!

  • Ravi, you are the best!

    A couple of simply questions (I hope):
    1) how is the left icon (three horizontal stripes) called?
    2) how can I change this icon / foreground color?

    Thank a lot for your precious help

    • hitesh

      1 ANS) The hamburger icon
      2 ANS) change the color in the color.xml in <item name=ascentcolor

  • Jaye

    Hi! Is this implementation of material design can run on kitkat and jellybean?

  • Ashwini

    Awesome tutorial…..So good

  • Monika

    Hello , I tried for Navigation drawer but it gives NullPointerException for

    drawerFragment.setUp(R.id.fragment_navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout), mToolbar);

  • keyur hudka

    is this code work in eclipse or not

    • Ramya Rajendran

      It works very well in eclipse

  • Ari Kusuma

    hi
    how if I want to add an icon?

  • Bhavik Shah

    Thank you for this tutorial. Now i want to add icons to recycleview or say to the NavigationDrawer. How can i do that?

  • Bhavik Shah

    How to add icons to Navigation Drawer?

  • Smiiil

    I used your tutorial. For some reason the array list links are not showing up. Drawer appears from left but is blank with white background. Any help?

  • Bhavik Shah

    Can we use Activity instead of Fragments?? please reply i am new to android and not much familiar with fragments.

    • Aditya Naik

      You can, but it is recommended to implement fragment from the beginning even if it’s only one layout. Easier to maintain in future. Try Google’s Android courses on Udacity. They are the most beginner friendly Android dev courses right now.

  • Krzysztof

    Hello, this is my error 🙁

    08-19 20:09:04.760 19021-19021/com.example.krzysztof.material8 E/AndroidRuntime﹕ FATAL EXCEPTION: main

    Process: com.example.krzysztof.material8, PID: 19021

    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.krzysztof.material8/com.example.krzysztof.material8.activity.MainActivity}: android.view.InflateException: Binary XML file line #35: Error inflating class fragment

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

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

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

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

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

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

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

    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:903)

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

    Caused by: android.view.InflateException: Binary XML file line #35: Error inflating class fragment

  • Kris

    Okay, greate code!! all is work!
    But i have a question: How add new position in menu?
    /Kris

    • Bhavik Shah

      Just add the values in array in string.xml

  • JongHyeok Park

    Is this works only in version called “Lolli pop” ???
    is this works in other lower version than lollipop?

    • Martijn Snijder

      Also pre-lollipop

  • Thanh Tú Lê

    Hi Ravi Tamada.

    I don’t know why auto back HomeFragment when rotate screen. How can prevent this.

    • Me too. And it doesn’t remember last fragment I visited if I close app and reopen

    • Loki

      Rotation messes things up.Also we have to use “retained fragments”. Basically when the orientation changes,the activity(or fragment in our case) is killed. That shouldn’t be happening. The tutorial is really good but it misses some parts.

    • Itallo Nardi

      Hello. I have created a variable called viewfragment, and instead of using DisplayView (0), I used DisplayView (viewfragment). In the switch, I did the following:

      switch (position) {

      case 0:

      CategoriesFragment fragment = new ();

      viewfragment = 0;

      title = getString (R.string.title_categories);

      break;

      case 1:

      SearchFragment fragment = new ();

      viewfragment = 1;

      title = getString (R.string.title_search);

      break;

      case 2:

      ConfigurationFragment fragment = new ();

      viewfragment = 2;

      title = getString (R.string.title_configuration);

      break;

      default:

      break;

      }

      I created the following method to save the value before the view is destroyed

      Override

      protected void onSaveInstanceState (Bundle OUTSTATE) {

      super.onSaveInstanceState (OUTSTATE);

      outState.putInt (“viewfragment” viewfragment);

      }

      and restored in the onCreate method, checking for any value except in savedInstanceState

      if (savedInstanceState! = null) {

      // Restore value of members from saved state

      viewfragment = savedInstanceState.getInt (“viewfragment”);

      } Else {

      viewfragment = 0;

      }

      This solved for me. Sorry for the bad English.

      • Okechukwu Eze

        Hi @itallonardi:disqus

        i tried this on my side and it didn’t work as u explained.
        Can u do me the favor of sending me ur AMENDED FILES or your COMPLETE AMENDED VERSION to my email :: okechukwu0127@gmail.com

        anticipating your response on my email.

        • Itallo Nardi

          Sorry, I could not fully understand the problem. I sent to your email. There are some additional things that are other methods, and is only remove. I’m not only saving the instance of the title, such as restoring the view of the current fragment. Your code is slightly different from mine.

          Sorry for the bad English.

          • Okechukwu Eze

            Thanks for the Mail.
            I have been able to figure out my little logical error on my own code.

            You are sure a life saver.

            Have you been able to Add an ICON/Image in front of the TExt on the Drawler view ?

      • Okechukwu Eze

        Hi @itallonardi:disqus
        I re-coded it again and this time, it doesn’t flag error but
        it still returns to the home activity-layout when the device orientation is changed.
        below is my codes

        ///////////////////////////////////////////////////////////////////

        //variable declaration
        private int viewfragment;

        ……………………………………………………….
        ……………………………………………………….

        //code from the onCreate method

        if (savedInstanceState!= null) {
        viewfragment = savedInstanceState.getInt (“viewfragment”);
        }
        else
        {
        // display the first navigation drawer view on app launch
        displayView(0);
        }

        ……………………………………………………….
        ……………………………………………………….

        //The onSaveInstanceState method
        @Override
        protected void onSaveInstanceState (Bundle outState) {

        super.onSaveInstanceState (outState);

        outState.putInt(“viewfragment”, viewfragment);

        }

        ……………………………………………………….
        ……………………………………………………….

        //also added the viewfragment here on all cases to capture the last state

        private void displayView(int position) {
        Fragment fragment = null;
        String title = getString(R.string.app_name);
        switch (position) {
        case 0:
        fragment = new HomeFragment();
        title = getString(R.string.title_home);
        viewfragment = 0;
        break;
        case 1:
        fragment = new FriendsFragment();
        title = getString(R.string.title_friends);
        viewfragment = 1;
        break;
        case 2:
        fragment = new MessagesFragment();
        title = getString(R.string.title_messages);
        viewfragment = 2;
        break;
        default:
        break;
        }

        Now u see i did exactly how u said u did it which u said worked for me.
        The BIG QUESTION IS
        What am i not doing right.

        Kindly respond or send me your version to my email :: okechukwu0127@gmail.com

      • Okechukwu Eze

        Hi @itallonardi:disqus

        Hahahahahah

        Nothing is as sweet as when you finally gets your program to work as u have always wished.

        Now its working. My code was correct, i have to uninstall the one on my device first, then re-install the new version and realized i was doing it right all the time.

        Thanks to @ravi8x:disqus and you for the inspiration

      • Okechukwu Eze

        @itallonardi:disqus
        i just realized that the title of the activity changed to “Material Design” which is the default APP NAME
        I edited your amendment to save the title instance but it did not work. check my code bellow
        .

        @Override
        protected void onSaveInstanceState (Bundle outState) {

        super.onSaveInstanceState (outState);

        outState.putInt(“viewfragment”, viewfragment);
        outState.putString(“viewfragmentTitle”,viewfragmentTitle);

        }

        …………………………………………………….
        ………………………………………………

        //from onCreate method

        if (savedInstanceState!= null) {
        viewfragment = savedInstanceState.getInt (“viewfragment”);
        viewfragmentTitle = savedInstanceState.getString(“viewfragmentTitle”);

        }
        else
        {
        // display the first navigation drawer view on app launch
        displayView(0);
        }

        …………………………………………………….
        ………………………………………………….

        //edited the displayView method for the title

        String title;

        if(viewfragmentTitle !=null)
        {
        title = viewfragmentTitle;

        }
        else {
        title = getString(R.string.app_name);
        }

        …………………………………………..

        That’s my version but the title returns to the default app name when the device oriantation
        changed.

        So what am i not doing right

    • My solution is pretty simple: When I select a fragment I save in preferences, and in displayview I load last fragment show (or 0 if first)

  • Hesah

    Hi ,,

    How can i add icons in the list view in the navigation ?

  • Tümer

    Hi,
    I would like to thank for your great tutorial.It’s very helpful.
    I added a userTimeline activity and layoyut extends fragment. I want to us Twitter fabric for showing userTimeline on my activity. I added a listview to my fragment_usertimeline

    fragment_usertimeline.xml

    FragmentUserTimeLine.java

    public class FragmentUserTimeLine extends ListFragment {
    public FragmentUserTimeLine() {
    // Required empty public constructor
    }

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

    TwitterSession session = Twitter.getSessionManager().getActiveSession();

    String userName = session.getUserName();

    final SearchTimeline searchTimeline = new SearchTimeline.Builder()
    .query(userName)
    .build();
    final TweetTimelineListAdapter adapter = new TweetTimelineListAdapter.Builder(getActivity())
    .setTimeline(searchTimeline)
    .build();
    setListAdapter(adapter);

    return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {

    super.onActivityCreated(savedInstanceState);
    View view = inflater.inflate(R.layout.fragment_usertimeline, container, false);
    }

    @Override
    public void onItemClick(AdapterView parent, View view, int position, long id) {
    }

    For using ListFragment i added a new case displayView method in my MainActivity.

    case 3:
    listFragment = new FragmentUserTimeLine();
    title = getString(R.string.title_timeline);

    if (listFragment != null)
    {

    FragmentManager fragmentManager = getSupportFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    fragmentTransaction.replace(R.id.container_body, listFragment);
    fragmentTransaction.commit();

    getSupportActionBar().setTitle(title);

    }

    But there is not working for showing UserTimeline. What’s my wrong ? Please help about this problem this is very important for me ?

  • Ajay Varma

    Ravi,
    Thanks for this great tutorial, it is working great. Now i have added PagerTabStrip as a child of ViewPager, and it is working fine with tabs and all, but as i click on the navigation drawer items. they doesn’t show up. Could you please help me out with this?
    Thank you

    • Bhavik Shah

      Hello Ajay,

      Can u please share me the code for PagerTabStrip With this tutorial

  • Đỗ Huy Hùng

    not working with api 10. Tell me how to do it? plz

    • Usanka Ranasinghe

      Material Design works with post API 21… That’s why

  • Bhavik Shah

    If i want to go from fragment 1 to another fragment 2 on click of a Button on Fragment 1

    • Aditya Naik

      You need to use the .replace() method of the FragmentTransaction class.
      Btw, you should always google before asking. Google and StackOverflow are our bffs. Happy coding! 🙂

  • Great article and very informative! Thx for sharing it.

    If you like you can give a look about my post where i describe how to code a weather app using material design (http://www.survivingwithandroid.com/2014/11/develop-android-weather-app-with-material-design.html)

  • How add a divider in left menu ?

  • Can It be possible to use webview in menu, I mean Is it possible to click on home and we can use our external layout in that ?

    • We can do that. But what is the purpose of loading a webview?

      If you want your navigation drawer menu dynamic, keep all the items in a json on the server, fetch the json and load the navigation drawer items.

      • thanks for your prompt reply. Can you please help me in this regards, How can i use that?

  • vishal

    Hi , Its good tutorial , Thanks for this , Want to know how to change the color of selected list here on left drawer .

  • Giuseppe

    hi, how do I open a search panel when I click on the magnifying glass on the toolbar? (Such as the YouTube app or Google I / O 2015)

  • madhur

    hii thanks for tutorial i found a error when clicked on navigation drawer it does not go to home fragment

  • Kunal Agrawal

    please provide the codes for using logout in Handle action bar

  • Murad Mohd Zain

    How add a divider in left menu ? Really need this

  • Vidyadhar Vidyuth K

    Can you please tell me how to add icons in the drawer list ??. i am a beginner and i am learning a lot from your tutorials.. thanks forth.

  • Mukesh Kumar

    Please suggest anyone, how can resolve this error..

    java.lang.NoSuchFieldError: No static field Theme_windowNoTitle of type I in class Landroid/support/v7/appcompat/R$styleable; or its superclasses (declaration of ‘android.support.v7.appcompat.R$styleable’ appears in /data/app/com.nssoftech.nsapps-2/base.apk)

    here is style.xml

    true
    false
    @color/colorPrimary
    @color/colorPrimaryDark
    @color/colorAccent

  • Prasad

    Thanks for the tutorial.

    Can you please tell me how to set the text in the Fragments from main activity ? I tried getting the reference of the fragment using fragment manager to call a method inside fragment class. But it does not work.

    I added this to displayView Case 0

    fragment= getFragmentManager().findFragmentById(R.id.fragment_all);
    fragment.setText(“My String”);

    SetText is the method I wrote in Fragment Class

    Any suggestions would be helpful . Thanks in Advance.

  • Murad Mohd Zain

    How to dynamically add divider between navigation items?

  • Is there a mistake in step 21? It says I should create the fragment under activity package, but then it tells I should right click adapter… so where do I need to create the fragment? In the activity package or in the adapter package?

    • Thanks for pointing that out. Corrected now. It should be under activity.

      • Yay, thank you for the fix! Great tutorial.

  • Okechukwu Eze

    I have been able to combine the MATERIAL DESIGN script and the SLIDING TABS tutorial into one App.

    Its really amazing to me how i can even do this combination since i am not even up to 2 months old with Android studio.

    Thanks to the detailed tutorial of @ravi8x:disqus

    You can download and improve on it from
    http://douxlms.com/quiz/materialdesign.zip

    Enjoy

  • 王锦

    thank u

  • Prakash Kumar

    Hi
    How can implement wcf service in android apps ..

    • Can you elaborate what wcf service is?

      • Prakash Kumar

        how can use wcf service(Wsdl web service ) in android mobile application.

        how can data parse using web service(wcf service/wsdl)
        ya using json format
        mainly he giving wcf web service and how can used android

        • Prakash Kumar

          using jason , get, post or jason parsing
          I don’t know how can us service
          please help me

      • Prakash Kumar

        Consuming Generated WCF Services in Android

  • Macharia

    Hi Ravi…,How do I use material for low end devices as 5.0 is too high for most users…,Does it use action bar..,I have looked for information and most does not guide in to when to use material and how to integrate with low end devices…,

    • Yes you can support this to lower end devices using Android Design Support Library as mentioned in this article

      http://www.androidhive.info/2015/09/android-material-design-working-with-tabs/

      • Macharia

        Great..,Thanks..,

      • Macharia

        Thank You I have been working on thus…,I am also confused on issues like bottom toolbar,coordinator layout,appbar and collapsing toolbar….,especially on how to implement botton toolbar like in facebook…,Kindly advise or a tutorial on your site would even be better.

  • Prashanth Debbadwar

    Can we have both Navigation Drawer and tabs in the same activity?

  • pavan kvch

    when i clicked on back the navigation drawer has to close but in my app
    it goes to previous activity, please help me how to close drawer not
    activity

  • Debie Trihartono

    Do you know how to make a selector for the list that we choose?

  • Humayoon

    can we set toolbar text center align as horizental and vertical

  • Владимир Круглов

    i have problem before point 3.3, log error:

    FATAL EXCEPTION: main
    java.lang.NullPointerException
    at com.example.ergo_proxy.goodlineapptest.fragments.FragmentDrawer$1.onClick(FragmentDrawer.java:90)
    at com.example.ergo_proxy.goodlineapptest.fragments.FragmentDrawer$RecyclerTouchListener.onInterceptTouchEvent(FragmentDrawer.java:188)

    What is that? Help pls

  • Saurabh Panchal

    What If i want to display HOME fragment by default also?i.e as “container_body”…What changes should I do?

  • Nali

    How Can I add Icon beside Text in every section?

  • Newbie

    Hi Ravi, Your tutorial is great. I am trying to use your tab with swipe material design in my app. I am using eclipse. I am not getting any error or warnings but the material theme is not applied in my app in tablet (Android 4.2), instead my app is with default theme with black notification bar. But in moto g handset theme is applied successfully. Any idea where would be the problem.

  • Vivek Mishra

    My drawer is not closing.If I press back button app exits

    • pavan kvch

      Same as my problem, when i click back it goes to previous activity

  • Macharia

    I am very confused on issues like bottom toolbar,coordinator layout,appbar and collapsing toolbar….,especially on how to implement botton toolbar like in facebook…,Kindly advise or a tutorial on your site would even be better.

  • Rahul Sharma

    CAN ANY ONE TELL ME HOW TO ADD IMAGES CORRESPONDING TO THE LIST

  • Rahul Sharma

    I mean images of home friends and messages in that list…..after clicking on navigation drawer

  • Lavekush Agrawal

    Hi Ravi, this is my first comment on your blog, you are awesome, always rock, and a big thanks to you for your selfless contribution.

    I have a confusion that why are using ActionBarActivity ? as you start this tutorial with Toolbar(Replacement of Actionbar), and ActionBar is deprecated so can you please clear me why are you using ActionBarActivity is there specific resion?

    • By the time of writing of this article ActionBarActivity is still in usage. Later it moved to AppCompatActivity. I have updated this article but still forgot in few places.

      I’ll update it today. Thanks for letting me know and I am glad that my blog helped you a lot 🙂

      Happy Coding!

      • Macharia

        Hello Ravi I have been following your tutorials…,I have a default landpage(HomeFragment) but one thing I have noted is on configuration change fragments go to home fragment instead of being retained…,how can I solve that…,

  • Anand

    Hi i want to add sub menus

  • Mostafa Aboali

    good work
    how i can chamge the icon in the toolbar that open the drawer ?

  • Ananda Sanhka

    Hi, travi nice work, but i noticed that for some reason my titles are not showing, it only shows the app title, what could be the problem.

  • olisa

    awesome post!!!!!

  • karthik

    Hi Ravi, your example was very pretty used for me, can you let me know how can we add along image with text in recyclerview

    • taimoor shaukat

      i need this code icon with text

  • brian migel

    hey thanx for the tut. but was inquiring how i could add icons in the navigation drawer

  • Josee Naava

    como agrego los iconos al navigation drawer

  • Gee En Clr

    hi Ravi, this is a very awesome post, but one thing I’m yet to accomplish is adding icons to the navigation drawer to this material design; help me accomplish this with the same code used here. Thanks much

  • Kalpak

    its a great post but my onclick event is not happning what should i look for?

  • Rupesh Kumar

    great tutorial it help me a lot but i am having problem to add icons with titles in the drawer. please help me.

  • varun mohan

    hi ravi,
    getting the following error at this line.

    drawerFragment = (FragmentDrawer)getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);

    Error:(31, 61) error: inconvertible types
    required: FragmentDrawer
    found: Fragment

    Please help.

    • varun mohan

      hi,

      solved it by replacing getSupportFragmentManager() with getFragmentManager().

      thanks

  • Prakash snigh

    Hi,

    This is really amazing article to get started with material design. But I am unable to download this Source code.

    Please help me guys, how to download this code……!

    Thanks in advance.

  • Juancho

    Thanks Ravi! Nice Tutorials

  • ATG

    Thanks Ravi.

  • anas rachmadi

    very useful tutorial thank you so much

  • zhx

    Hi thanks for your tutorial. I just start to learn android development. I followed your post to test, but I found my project’s activities_main.xml is different from yours. There is another file content_main.xml. Where to put the toolbar code?

    • Chirag Savsani

      Because In this example he use AndroidStudio new version,
      In new AndroidStudio, when user creates new projects content_main.xml file will created automatically with activity_main.

  • armmin

    why clickable nav item in recyclerview??

  • armmin

    why use this app in lower android (2.2)?

  • I have error when sync gradle and my R.java is missing. How to fix it. I was clean and rebuild project but nothing happen.

    AGPBI: {“kind”:”ERROR”,”text”:”Error retrieving parent for item: No resource found that matches the given name u0027android:TextAppearance.Material.Widget.Button.Inverseu0027.”,”sourcePath”:”/home/arifh/Downloads/MaterialDesign/MaterialDesign/app/build/intermediates/exploded-aar/com.android.support/appcompat-v7/23.1.0/res/values-v23/values-v23.xml”,”position”:{“startLine”:1},”original”:””}

    AGPBI: {“kind”:”ERROR”,”text”:”Error retrieving parent for item: No resource found that matches the given name u0027android:Widget.Material.Button.Coloredu0027.”,”sourcePath”:”/home/arifh/Downloads/MaterialDesign/MaterialDesign/app/build/intermediates/exploded-aar/com.android.support/appcompat-v7/23.1.0/res/values-v23/values-v23.xml”,”position”:{“startLine”:1},”original”:””}

    Error:Execution failed for task ‘:app:processDebugResources’.
    > com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process ‘command ‘/home/arifh/android-sdk-linux/build-tools/23.0.2/aapt” finished with non-zero exit value 1

    • Just import com.yourpackage.R and it will work

      • My problem solved. I just update to latest Android Studio. Thanks.

  • My navigation drawer appears behind the action bar and content on the screen. Help here please

  • Jay

    I can u give me codes on how to highlight the item..

  • briza

    Hi ravi iam having problem with drawer fragment because i want the navigation drawer list to be highlighted when there is a fragment , in other tutorials they use listview but on this tutorial you use drawerfragment need help to highlight existing fragment 😀

    • briza

      @ravi8x:disqus help

  • Clarence

    Hello Ravi, I need your help in adding icons to the navigation drawer in this particular tutorial. its really urgent.
    PS: Don’t forsake a brother.

    • PANKAJ PUROHIT

      If this is not late then Add imageview in nav_drawer_row.xml.And make changes in NavigationDrawerAdapter.java for imageview. If you are working with android then you can go ahead from this hint.

      • clarence

        thanks, but I have tried that approach and I get the first icon been repeated simultaneously in each fragment in the drawer. if you could help with adding the code I’d be entirely grateful, cuz I don’t know what to do at the moment.

        • Murage Wanjohi

          Implement it just like in Ravi’s previous tutorial (http://www.androidhive.info/2013/11/android-sliding-menu-using-navigation-drawer/)

          1. ) Add an ImageView on nav_drawer_row.xml
          2.) Add an int icon variable, getter and setter on NavDrawerItem.java
          3.) Add an ImageView in MyViewHolder in NavigationDrawerAdapter and set the ImageResource (see how TextView has been implemented)
          4.) Add a Nav Drawer Item Icons array in your string.xml
          (Implemented in the above link)
          5.) Add a TypedArray navMenuIcons variable in FragmentDrawer.java
          6.) Add the following line in the List getData() method,
          below navItem.setTitle(titles[i]);
          navItem.setIcon(navMenuIcons.getResourceId(i,i));
          7.) Add the following line on the onCreate method,
          navMenuIcons = getResources()
          .obtainTypedArray(R.array.nav_drawer_icons);

          8.) Got everything from Ravi’s above tutorial. Thanks Ravi for your great and detailed tutorials.

          • Clarence

            Thanks a lot mate, it worked liked magic. 🙂 i’m truly grateful.

          • @rpit Patel

            i am getting error NavigationAdapter please help me

            ERROR

            android.view.InflateException: Binary XML file line #23: Error inflating class image_drawer

            at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:713)

            at android.view.LayoutInflater.rInflate(LayoutInflater.java:761)

            at android.view.LayoutInflater.inflate(LayoutInflater.java:498)

            at android.view.LayoutInflater.inflate(LayoutInflater.java:398)

            at info.androidhive.materialdesign.adapter.NavigationDrawerAdapter.onCreateViewHolder(NavigationDrawerAdapter.java:38)

            at info.androidhive.materialdesign.adapter.NavigationDrawerAdapter.onCreateViewHolder(NavigationDrawerAdapter.java:20)

            at android.support.v7.widget.RecyclerView$Adapter.createViewHolder(RecyclerView.java:5116)

            at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:4416)

            at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:4326)

            at android.support.v7.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:1955)

            at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1364)

            at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1327)

            at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:556)

            at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:2713)

            at android.support.v7.widget.RecyclerView.onLayout(RecyclerView.java:3011)

            at android.view.View.layout(View.java:15903)

            at android.view.ViewGroup.layout(ViewGroup.java:4932)

            at android.widget.RelativeLayout.onLayout(RelativeLayout.java:1055)

            at android.view.View.layout(View.java:15903)

            at android.view.ViewGroup.layout(ViewGroup.java:4932)

            at android.support.v4.widget.DrawerLayout.onLayout(DrawerLayout.java:931)

            at android.view.View.layout(View.java:15903)

            at android.view.ViewGroup.layout(ViewGroup.java:4932)

            at android.widget.FrameLayout.layoutChildren(FrameLayout.java:453)

            at android.widget.FrameLayout.onLayout(FrameLayout.java:388)

            at android.view.View.layout(View.java:15903)

            at android.view.ViewGroup.layout(ViewGroup.java:4932)

            at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1692)

            at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1534)

            at android.widget.LinearLayout.onLayout(LinearLayout.java:1443)

            at android.view.View.layout(View.java:15903)

            at android.view.ViewGroup.layout(ViewGroup.java:4932)

            at android.widget.FrameLayout.layoutChildren(FrameLayout.java:453)

            at android.widget.FrameLayout.onLayout(FrameLayout.java:388)

            at android.view.View.layout(View.java:15903)

            at android.view.ViewGroup.layout(ViewGroup.java:4932)

            at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1692)

            at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1534)

            at android.widget.LinearLayout.onLayout(LinearLayout.java:1443)

            at android.view.View.layout(View.java:15903)

            at android.view.ViewGroup.layout(ViewGroup.java:4932)

            at android.widget.FrameLayout.layoutChildren(FrameLayout.java:453)

            at android.widget.FrameLayout.onLayout(FrameLayout.java:388)

            at android.view.View.layout(View.java:15903)

            at android.view.ViewGroup.layout(ViewGroup.java:4932)

            at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2418)

            at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2133)

            at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1297)

            at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6773)

            at android.view.Choreographer$CallbackRecord.run(Choreographer.java:813)

            at android.view.Choreographer.doCallbacks(Choreographer.java:613)

            at android.view.Choreographer.doFrame(Choreographer.java:583)

            at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:799)

            at android.os.Handler.handleCallback(Handler.java:733)

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

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

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

            at java.lang.reflect.Me

          • surya

            Thanks murage… after spending a hour i found urs code.. and it worked like a charm !!!!

          • taimoor shaukat

            hy can you send me code how to add icon in navigation

  • Hamees Arshad

    i am following material design tutorial as step no 6 mention above when i run the project it gives me Error:(11, 5) No resource found that matches the given name: attr ‘windowNoTitle’.

  • Reshmi James

    Thank you very much for this excellent tutorial! Worked like a charm.

    • You are welcome 🙂

      • Reshmi James

        Hi, Would like to clarify a question I have regarding the touch listener of the RecycleView. Why do we create a separate RecyclerTouchListener and do gestureDetection within its constructor? Can we simply not use the RecyclerView.OnItemTouchListener and add this code

        public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {

        View child = rv.findChildViewUnder(e.getX(), e.getY());
        if (child != null && clickListener != null) {
        clickListener.onClick(child, rv.getChildPosition(child));
        }
        return false;
        }

        I’m sure there is a good reason for adding gestureDetection which I’m missing. Would appreciate of you could throw some light. Thanks again for your brilliant effort in creating these tutorials!

  • Jordi Masip

    Great tutorial! Thank you very much! But the app exits if I press back button. Do you know how to fix it?

  • Dylan Hyslop

    Would someone like to comment on the two design approaches: 1: load each screen as a Fragment into the main Activity, vs 2: Using a new activity for each screen.

    • ARASHI Funsho

      if you will implement the navigation drawer for an activity, you have to use fragments.

      Learnt this the hard way…. and couldn’t convert my loads of activities into fragment

  • Emmett Daly

    Thank you, I found this tutorial to be very useful. You explained the process a lot more clearly than other tutorials online, where you’re expected to download and apply the code. Here, you actually talked through the correct process in a clear and concise manner. Thanks again.

  • I have this Message: 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.

    • sathya narayanan
    • sathya narayanan

      try this in

  • sathya narayanan

    Great tutorial! Thank you very much! But the app exits if I press back button. Do you know how to fix it?

    • @rpit Patel

      handle onBackpress() method in Mainactivity

  • Osinnowo Emmanuel

    I don’t how much I should thank you, this is the greatest tutorial ever seen, it is very comprehensive and concise compare to other tutorials I have been seeing, I came here out of frustration and I got it all, thank you once again, you’re a great Teacher. Thanks.

    • ARASHI Funsho

      Yup….. trained me up to intermediate level in no time……..

  • ponco robbi

    very helpful, thanks!

  • Deepak Sharma

    How Can I lock the drawer when on item click ?

  • indrajit narvekar

    Very first time I used this tutorial and made my Material design successfully…

    Thanks alot …..whoever made this
    …………………………………………………………………………
    thanks…

  • sanju davariya

    please more elaborate step no:-12

    • Khiem Nguyen Dang

      u go to in your project. Create manual folder menu when it will show on Android Studio

  • Cyril Ferrand

    Nice job, Thanks !

    But…I try to share drawer in a base activiy Class but I have a strange error :
    java.lang.IllegalArgumentException: No view found for id 0x7f0e006c (com.facades_de_nice.fdnapplication:id/container_body) for fragment HomeFragment

    • Clean the project and run again.

      • Cyril Ferrand

        Same 🙁
        But I make code modification to have MainActivity extends BaseActivity, maybe a problem of lifecycle…My new MainActivity only contain the OnCreate method :

        protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        // display the first navigation drawer view on app launch

        displayView(0);

        }

        • Cyril Ferrand

          I find it !
          I forget super.setContentView(layoutResID); in my override setContentView…
          Shame on me

  • Arihant Jain

    hello ravi sir ,

    I implement above code in eclipse and android studio both but in both i get this error please help me how to resove this issue

    02-03 23:49:13.499: E/AndroidRuntime(1829): FATAL EXCEPTION: main

    02-03 23:49:13.499: E/AndroidRuntime(1829): Process: com.example.materialdesign, PID: 1829

    02-03 23:49:13.499: E/AndroidRuntime(1829): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.materialdesign/com.example.materialdesign.MainActivity}: android.view.InflateException: Binary XML file line #35: Error inflating class fragment

    02-03 23:49:13.499: E/AndroidRuntime(1829): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2184)

    02-03 23:49:13.499: E/AndroidRuntime(1829): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)

    02-03 23:49:13.499: E/AndroidRuntime(1829): at android.app.ActivityThread.access$800(ActivityThread.java:135)

    02-03 23:49:13.499: E/AndroidRuntime(1829): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)

    02-03 23:49:13.499: E/AndroidRuntime(1829): at android.os.Handler.dispatchMessage(Handler.java:102)

    02-03 23:49:13.499: E/AndroidRuntime(1829): at android.os.Looper.loop(Looper.java:136)

    02-03 23:49:13.499: E/AndroidRuntime(1829): at android.app.ActivityThread.main(ActivityThread.java:5001)

    02-03 23:49:13.499: E/AndroidRuntime(1829): at java.lang.reflect.Method.invokeNative(Native Method)

    02-03 23:49:13.499: E/AndroidRuntime(1829): at java.lang.reflect.Method.invoke(Method.java:515)

    02-03 23:49:13.499: E/AndroidRuntime(1829): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)

    02-03 23:49:13.499: E/AndroidRuntime(1829): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)

    02-03 23:49:13.499: E/AndroidRuntime(1829): at dalvik.system.NativeStart.main(Native Method)

    02-03 23:49:13.499: E/AndroidRuntime(1829): Caused by: android.view.InflateException: Binary XML file line #35: Error inflating class fragment

    02-03 23:49:13.499: E/AndroidRuntime(1829): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:713)

    02-03 23:49:13.499: E/AndroidRuntime(1829): at android.view.LayoutInflater.rInflate(LayoutInflater.java:755)

    02-03 23:49:13.499: E/AndroidRuntime(1829): at android.view.LayoutInflater.inflate(LayoutInflater.java:492)

    02-03 23:49:13.499: E/AndroidRuntime(1829): at android.view.LayoutInflater.inflate(LayoutInflater.java:397)

    02-03 23:49:13.499: E/AndroidRuntime(1829): at android.view.LayoutInflater.inflate(LayoutInflater.java:353)

    02-03 23:49:13.499: E/AndroidRuntime(1829): at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:256)

    02-03 23:49:13.499: E/AndroidRuntime(1829): at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:109)

    02-03 23:49:13.499: E/AndroidRuntime(1829): at com.example.materialdesign.MainActivity.onCreate(MainActivity.java:28)

    02-03 23:49:13.499: E/AndroidRuntime(1829): at android.app.Activity.performCreate(Activity.java:5231)

    02-03 23:49:13.499: E/AndroidRuntime(1829): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)

    02-03 23:49:13.499: E/AndroidRuntime(1829): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2148)

    02-03 23:49:13.499: E/AndroidRuntime(1829): … 11 more

    02-03 23:49:13.499: E/AndroidRuntime(1829): Caused by: android.app.Fragment$InstantiationException: Unable to instantiate fragment com.example.materialdesign.activity.FragmentDrawer: make sure class name exists, is public, and has an empty constructor that is public

    02-03 23:49:13.499: E/AndroidRuntime(1829): at android.app.Fragment.instantiate(Fragment.java:597)

    02-03 23:49:13.499: E/AndroidRuntime(1829): at android.app.Fragment.instantiate(Fragment.java:561)

    02-03 23:49:13.499: E/AndroidRuntime(1829): at android.app.Activity.onCreateView(Activity.java:4778)

    02-03 23:49:13.499: E/AndroidRuntime(1829): at android.support.v4.app.BaseFragmentActivityHoneycomb.onCreateView(BaseFragmentActivityHoneycomb.java:34)

    02-03 23:49:13.499: E/AndroidRuntime(1829): at android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:79)

    02-03 23:49:13.499: E/AndroidRuntime(1829): at com.example.materialdesign.MainActivity.onCreateView(MainActivity.java:1)

    02-03 23:49:13.499: E/AndroidRuntime(1829): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:689)

    02-03 23:49:13.499: E/AndroidRuntime(1829): … 21 more

    02-03 23:49:13.499: E/AndroidRuntime(1829): Caused by: java.lang.ClassNotFoundException: Didn’t find class “com.example.materialdesign.activity.FragmentDrawer” on path: DexPathList[[zip file “/data/app/com.example.materialdesign-1.apk”],nativeLibraryDirectories=[/data/app-lib/com.example.materialdesign-1, /system/lib]]

    02-03 23:49:13.499: E/AndroidRuntime(1829): at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)

    02-03 23:49:13.499: E/AndroidRuntime(1829): at java.lang.ClassLoader.loadClass(ClassLoader.java:497)

    02-03 23:49:13.499: E/AndroidRuntime(1829): at java.lang.ClassLoader.loadClass(ClassLoader.java:457)

    02-03 23:49:13.499: E/AndroidRuntime(1829): at android.app.Fragment.instantiate(Fragment.java:583)

    • Clean the project from Build -> Clean and try again.

    • Arihant Jain

      Thanks for the example it works fine in android studio

  • Very well explained guide on material design finally I found.

  • Appkart In

    Hi Ravi, Why android:layout_gravity=”start” is used here. Please help because i did not understand

    • Chirag thaker

      Because Navigation Drawer Appear from Left side, after Android L update they upgrade Gravity : Left to Start and Right to End

  • Chirag thaker

    Nice Tutorial about Nav.Drawer . One Side Question in android studio what “Invalid cache and restart does”

  • Clay24g

    This is a tutorial any android developer should follow. Material design is amazing. Thanks, man!

  • sagarS

    Hello Ravi Sir,
    This code is really helpful for me and very easy to understand.
    I want to hide navigation drawer icon from some fragments or from main activity.
    How to achieve it?
    please guide me.

  • Abhin

    I got an error like “Resource not found colorPrimary”

    “Resource not found colorPrimaryDark”

    • Rick

      same thing here… plus there are so many other things which is giving me errors like Version, minSdkRequired and others.. don’t know how to resolve them.. what to do??
      Suggestions needed…. Anybody?? or @ravi8x:disqus ??

      • sagarS

        try with older appcompat version:
        compile ‘com.android.support:appcompat-v7:22.2.1’

    • JosephAb

      check you colors.xml file inside values folder. inside that create a new resource as

      #F44336(hex code of color you want)

      Hope this helps 🙂

  • Uyi Oriaghan

    Hello guys pls i need your help at step 20.
    after creating a class named NavigationDrawerAdapter.java and pasted the codes i had this error:

    Error:(16, 10) error: cannot find symbol class NavDrawerItem
    Error:(20, 58) error: cannot find symbol class NavDrawerItem
    Error:(33, 39) error: package R does not exist
    Error:(40, 9) error: cannot find symbol class NavDrawerItem
    Error:(54, 55) error: package R does not exist
    Error:Execution failed for task ‘:app:compileDebugJava’.
    > Compilation failed; see the compiler error output for details.
    Information:BUILD FAILED

    Please help me, this tutorial has been really interesting..
    Thanks.

    • JosephAb

      Do not copy and paste the entire code. NavDrawerItem must be in model subpakage inside your application main package file. So when importing that java class ,you have to give the correct path to it also. Eg: if you created the java class NavDrawerItem inside Model package then you must import as- import “yourpackagename”.model.NavDrawerItem , Hope this helps 🙂

      • Uyi Oriaghan

        Thanks so much, ive been able to fix it. but i also wanna ask the items in d recylceView in the NavDrawer i.e the HOME, FRIENDS ,MESSAGES, how do we make it highlight when its touched

  • Uyi Oriaghan

    Hello guys pls i need your help at step 20. After creating a class named NavigationDrawerAdapter.java and pasted the codes i had this error:
    Error:(16, 10) error: cannot find symbol class NavDrawerItem
    Error:(20, 58) error: cannot find symbol class NavDrawerItem
    Error:(33, 39) error: package R does not exist
    Error:(40, 9) error: cannot find symbol class NavDrawerItem
    Error:(54, 55) error: package R does not exist
    Error:Execution failed for task ‘:app:compileDebugJava’.
    > Compilation failed; see the compiler error output for details.
    Information:BUILD FAILED

    Please help me, this tutorial has been really interesting..
    Thanks.

    • fadejimi

      At first you have to create the NavDrawerItem class and it should be in your model class, if it is there then you have to import the package name.
      If you are using android studio just right click on the error(33,39) and import the package of your application like uyi.app.materialdesign depending on how you named your application.

  • Manny264

    Ravi, please help. How can I group the items on the nav drawer? I mean I already have a menu resource file with different groups. How and where do I set this group?

  • aslam

    hi sir how to add icon in navigation drawer

  • vinod

    sir, can we write navigation drawer item’s in telugu language????

  • aman

    how to change text color of navigation item or background of that item when selected.

  • Jordan

    I’m on step 23 and I got this error :

    Attempt to invoke virtual method ‘void android.widget.TextView.setText(java.lang.CharSequence)’ on a null object reference

    at mypackage.adapter.NavigationDrawerAdapter$override.onBindViewHolder(NavigationDrawerAdapter.java:47)

  • Roy Zack

    How to change the Title Text color i change the “textColorPrimary” but it still remain the same color white…. did the tutorial missing some variable for the theme?

  • eduardo

    Building “MaterialDesign” Gradle project info and building, building and building 🙂

  • Yashwant Chawhan

    How to make navigation drawer right to left, any idea??

    • Nijesh Narayanan

      just set navigation drawer alignment to left

  • reva3260

    Hello ,

    I download my fragment list “tiles” from Firebase.
    and make a string like this

    titles = new String[5];
    titles[0] = title0; (title0 is a variable containing a value of the database)
    titles[1] = title1;
    titles[2] = tile2;
    titles[3] = tile3;

    If I make my String array in FragmentDrawer.java – onCreate Void I take Fatal Exception error.

    I would like to know how I could make this array in MainActivity and take the data in FragmentDrawer.java.

    Actually I would like to replace the following command

    titles = getActivity().getResources().getStringArray(R.array.nav_drawer_labels);

    and make the titles list dynamically.
    Thanx
    RE

  • Ashwath

    whenever i click on home, it gives “Unfortunately, theapp has stopped”.Why so?

  • amine

    thanks man, very nice job

  • Shraddha

    hello, ur tutorial is really great. i want a help …… how to add icons to row item , m unable to do it. pls help asap

    • Rick

      Shraddha I’m not so expert with Android yet but if I’m not wrong in understanding your question, then you might need to do something like this:

      private void setupTabIcons() {
      tabLayout.getTabAt(0).setIcon(tabIcons[0]);
      tabLayout.getTabAt(1).setIcon(tabIcons[1]);
      tabLayout.getTabAt(2).setIcon(tabIcons[2]);
      }

      so prepare your icons in drawable folder and link them there.

      Hope this will help.

      For more info, go to @ravi8x:disqus http://www.androidhive.info/20… tutorial.. you will find details there..

      Cheers!

  • hamid reza

    thanks alot

  • Arihant Jain

    hello, ur tutorial is really great. i want a help …… how to add icons to row item , i am unable to do it. pls help asap

    • Rick

      Arihant Jain I’m not so expert with Android yet but if I’m not wrong in understanding your question, then you might need to do something like this:

      private void setupTabIcons() {
      tabLayout.getTabAt(0).setIcon(tabIcons[0]);
      tabLayout.getTabAt(1).setIcon(tabIcons[1]);
      tabLayout.getTabAt(2).setIcon(tabIcons[2]);
      }

      so prepare your icons in drawable folder and link them there.
      Hope this will help.

      For more info, go to @ravi8x:disqus http://www.androidhive.info/2015/09/android-material-design-working-with-tabs/ tutorial.. you will find details there..

      Cheers!

  • msroid

    hi, It’s really great job.
    i have a question. how can i add a separator or a section to the drawer?
    for example i have 5 items and i need a separator after third item.

  • heyy boss i am new in android development would you please tell me how can i create a app using material design and fetch data of blogger.

    or is there any way that i download the xml file from blogger and insert it into my android app

    but i want to create a fully automatic app whenever i post on blogger my app automaticall updated

    Please suggest me I will wait for your answer

  • This is really helpful! Thanks!

  • raveena

    Failed to find the style corresponding to the id 2130772027

    Failed to convert ?attr/colorPrimary into a drawable

    “?attr/actionBarSize” in attribute “minHeight” is not a valid format.

    Exception details are logged in Window > Show View > Error Log
    come in error in layout of main

    • Nicky N

      still having the problem?

  • August

    successfully done this tutorial. thank you 🙂

    • You are welcome 🙂

      • Karthi9474@gmail.com

        how to set navigation drawer list icon????

  • Bruno Chichava

    It works, great tutorial! God Bless.

  • Muhammad Sufiyan

    really great post, helped me a lot.. and others posts too are great, 🙂

  • Maher Nabeel

    by providing to us such well explained tutorials, you’re truly a successful person. Thanks man.

  • Ivan

    Beautiful tutorial. Thanks!

  • Meshileya Israel

    Thanks for this amazing tutorials…..really appreciates

  • maxx

    How to add the menu content dynamically? Bcz I am getting the content from the Rest API, So it will change dynamically, So can you please guide this.

  • Sam

    Hi Ravi,

    is there a way to handle the back button?

    • Nicky N

      finish();

  • Bruno Logerfo

    Thanks, nice tutorial!

    • Nicky N

      is there any error?
      go and check your string.xml folder you might have missed this

      @string/nav_item_home
      <!–@string/nav_item_movies –>

      @string/nav_item_friends
      @string/nav_item_notifications
      @string/nav_item_logout

      • Bruno Logerfo

        sorry, solved already, forgot to edit my comment. thanks =)

  • Rohit Dhepe

    Hi Ravi, very nice tutorial and I am using it almost for all the apps I am working on, just came across one situation that how to highlight the navigation drawer menu item. Thanks in advance.

  • Mateusz

    Hi Ravi is it possible to add google map into one of these three fragments ? If Yes could You tell how ? I am trying and trying and nothing…

    • Which article you are following to implement maps?

  • Unil Gandhi

    Hi Ravi, i have followed many of your examples. My question is that why have you used a separate fragment for the navigation drawer whereas in your navigation drawer example you created the drawer directly. What is the difference between the two methods?

  • Nitin Bhanushali

    hey i want to make recycler view into fragment.can you please suggest how it will possible ?

  • NEha

    Hi Ravi, Is there any way of doing a material design concept in eclipse android. ? Is it possible to implement the same in Eclipse Android?

    • Nicky N

      Why are you still using Eclipse?.
      You can but with a lot of coding. You should migrate your project to Android Studio. If you need any help…

  • mojtaba aghasizadeh

    Hi Tamada
    thank u for your post
    how i can move the menu to left and drawer to right in the toolbar
    tanks a lot…

  • radz

    Can i use activity in place of fragment?

    • Nicky N

      yes you can.but its advised you use fragments.

  • August

    Hi Ravi. As add more items in drawer, it become laggy. Any solution?

    • Nicky N

      mine doesnt. check your device memory

    • Atula

      facing same issue with big screen devices

  • Robel Alemu

    Hi Ravi , I was wondering how would it be possible to support devices with lower android versions when working with material design. Like for example if i have a floating button on my app and the user is using android 2.1 , what will happen.

  • Jessie Semana

    Hi Sir Ravi. Thanks for this tut. I have just one question.:)
    How do the example above adopts whether your theme is Light or Dark? I found out that when you remove the background in fragment_navigation_drawer.xml, it messes up the drawer where the background of your main app and the drawer are the same. Any suggestions?

  • Sujan Lamichhane

    Hello Ravi Sir, Thanks for awesome example. I have a problem that Icons are not shown on the navigation drawer. Please help me to show Icons on nav drawer.

  • Karthi9474@gmail.com

    nice tutorial thank you Ravi,
    I need an how to add Navigation drawer icon ???? can you please suggest me..

    • Toqeer

      can you suggest me how to add icon in navigation drawer

      • taimoor shaukat

        same issue how to icon in navigation list

        • Atula

          you need to update your NavigationDrawerAdapter like
          NavigationDrawerAdapter adapter = new NavigationDrawerAdapter(getActivity(), getData(), image);
          where image may be an arraylist or a String array and update your adapter layout with image and text rather then text as given in the tutorial.
          then get this arraylist in adapter and set image there just as titles.

  • Denis Eldorado

    I am getting only one item in the navigation drawer(only “home”) how do I add more items???

    • Nicky N

      goto strings

  • Ilyasa

    how to add toolbars?

  • peerzada burhan

    Awesome tutorials ..
    Check my Material Design tutorials app here :
    https://play.google.com/store/apps/details?id=com.pzbproduction.burhan.materialdesigntutorials
    Thank you 🙂

  • pranav m.s

    Thanks Ravi Tamada .Its really helpful for people like me.

  • manzoor926

    i wanted to add on more menu Find with home, friend and message . where i will change in the code

    • osama akb

      in the string file add one more item

  • taimoor shaukat

    how to add back button in friend and message fragment when press back button go to home fragmant

    • Nicky N

      create a back button and try to use finish();

  • Bagues Danang S

    thanks helpful

  • Sepehr Azizi

    Nice but how can i add icons beside navigation drawer items ???

  • Nezih

    Thanks for tutorial Ravi. I have a question, what is difference between the Navigation Drawer Activitiy and your tutorial ? Which one should we use ? Thanks.

    • Nicky N

      Navigation Drawer “Activitiy” has acivities as its means of displaying views , this tutorial has Navigation Drawer “Fragments” which uses fragments. Fragments are recommended here in Navigation Drawer because they are awesome. lemme quote Bob from stack overflow .

      “Fragments are more of a UI benefit in my opinion. It’s convenient for the user sometimes to see two different views of two different classes on the same screen. If, in your moment of creativity, you decide it would be nice to display your application with, say, a listView that takes up half the screen and a webView that takes up the other half – so that when you click on a list item in fragment A it passes an intent to the webView in fragment B, and suddenly you see what you just clicked without the app switching activities – then you could use a fragment. That’s just an example I came up with off the top of my head.

      Bottom line: Fragments are two or more activities on the screen at the same time.”

      Hope you understand

  • Anand Saxena

    Can you post or suggest a tutorial for Co-ordinator Layout???

  • Sean O’Connor

    How do i reduce the size between the navigation items(home, messages, friends)? At the moment only Home is visible and to see the others I have to scroll down?

  • Nazar

    I thought I’m gonna learn about material stuff but it turned out to be about navigation drawer

  • Bruno Chichava

    Hi Ravi, sorry for my english, i am mozambicain, recently I downloaded the new version of Android Studio, so that when I create a new project, the screens that create appear already with a default appbar, I do not know how to take, and when I try to put as in the tutorial is underneath that bar app, as can I fix this? Already tried almost everything, even this tutorial is not working for me, thanks in advance.

  • Neha Sharma

    Hello Ravi Sir.. I am very much interested to work with Material Design . Can You Suggest a tutorial or any website or any blog so that I can get more on Material design. Actually I want to cover maximum to maximum part of Material Design.

    • There is no such thing that covers every topic. You need to learn them from different websites or you can find a Udemy video series which covers everything.

  • rakesh kushwaha

    sir, in 6.0 toolbar showing in white color.plz tell me soloution wats the problem????? thnks!

  • Ibrahim Samad

    Hello Ravi, my application is displaying only “Home” menu item the rest of the menu items; “Friends and Messages” are not displaying. But I have crossed checked my string files to see they exist. And the for loop in the FragmentDrawer is also intact. What might be wrong?

    Thanks!

  • Try Catch Do Nothing

    I was able to get this to work using Xamarin and .Net. Thanks!

  • Dharam singh

    I am getting this error can any one help me???

    Error:(16, 24) No resource found that matches the given name (at ‘theme’ with value ‘@style/AppTheme’).
    Error:Execution failed for task ‘:app:processDebugResources’.
    > com.android.ide.common.process.ProcessException: Failed to execute aapt

  • Viral Patel

    Hi, I am using this tutorial but i am having one problem when i go to any fragment from main activity and then if i have to come to main activity again it not sending me back application close if i press back button.

    Please help me..

    • Henk

      That is because an fragment is hosted inside an activity, so it does not standard respond to a backbutton press.
      You can override onBackPressed (ctrl+o) in your fragment, so it calls that function first and do your logic from there.

  • Dave Byrne

    I got as far as step 12 where it was saying to go to the menu folder in res. I’m using AS ver. 2.2.2 and have not ever seen a menu folder in res. I created one and tried to put in the main_menu.xml but it forces the file to go into either layout or values. Also, I could not create this project with Blank Activity as that is no longer an option, perhaps that has some baring on the menu issue. Any help appreciated.

    • Yes, when you create a new file it mights goes to another folder. You can just drag and drop that file into menu folder. Android Studio changes it’s follow from version to version.

      • Dave Byrne

        Thank you, problem solved. A new issue now though. When I open each fragment for Home, Friends or Messages, it is returning a black screen with none of the fragment_home, fragment_friends or fragment_messages layout (i.e. HOME Edit fragment_home.xml to change the appearance). It seems to be because in the MainActivity it will not accept Fragment fragment as a new HomeFragment, FriendsFragment or MessagesFragment.
        https://uploads.disquscdn.com/images/022eedcc9b04d6ba70169c886eea00b4e1c66cef633498757b60fd19b73f6629.png

        • You need to import correct .Fragment statement in all the activities. Check you can importing it with and without support.v4

  • Android Getting Started with Material Design

  • Briandito Priambodo

    thank you for the tutorial, it has helped me a lot 🙂

  • Atula

    hi Ravi ,
    I am facing an issue with speed and can’t figure it out.
    My Problem is that this navigation drawer works good on small screen devices but get slower on big screen devices. Can you help me in that?

    • Atula

      Hi Ravi can’t you help in this..?

      • May be the lag is because of fragments you are loading when navigation drawer is selected.

  • Arvind Kumar

    Hi Ravi,
    Your Tutorials are awesome thanks ,it helps me a lot to learn android.
    Currently i am working on video compression and upload that video to server .

    Do you have any video compression tutorial ? Please upload

    • Sorry Arvind, i don’t have any tutorials. Even I have to start exploring in that area.

      • Arvind Kumar

        Thanks for reply

  • Nishant Patel

    Hiii Ravi..I am Nishant patel.I am working in Velocis system pvt. Ltd.I am beginner for app development. Can you suggest me which site i prefer for layout design..

  • Senthil S. Natarajan

    Ravi – thanks a lot for this tutorial. One q: How would we change the font typeface of the toolbar labels?

  • Mayank Pathak

    You have not using navigation view widget. Is using navigation view widget a better way to do this.

  • George Odongo

    Thanks Ravi, the tutorial is fantastic and helps understand how everything works under the hood. Is there any advantage of using this approach than using the ready made Navigation Drawer Activity template when you’re a creating a new project, as pointed out by Mayank Pathak.

    • Hi George,

      You can definitely go head with Navigation Drawer template. But this article is to understand the underlaying mechanism that Material Design use so that you will be able to do any customization that is needed.

      I hope you went through this article too.
      http://www.androidhive.info/2013/11/android-sliding-menu-using-navigation-drawer/

      • George Odongo

        The tutorial was quite helpful, I did manage to get everything working from start to finish. Once again thanks, keep it up.

        • You are welcome 🙂

          • George Odongo

            What is the best way of reusing the Navigation Drawer in other activities?

            Thanks!

  • hi Ravi
    I’m hi to you on behalf of all Iranian people
    You are indeed a master
    I really thank you.

  • Aseem Shrivastava

    Hello Ravi,
    my container_body is not replaciing the HOME_Fragment To any other.

    • Joseph

      @Override
      public void onDrawerItemSelected(View view, int position) {
      displayView(position);
      }

      Update your Main Activity with this

  • Nur Uddin

    I’m getting this error = “java.lang.ClassCastException: android.widget.RelativeLayout cannot be cast to android.support.v4.widget.DrawerLayout”
    how can i solve this issue

  • hey, thanks for this useful tutorial… now what if i want to add a tab design into fragment_friend ?

  • William McInroe

    I have a custom Toolbar, and cannot find how to customize or change ; the ‘3 dot’ Menu item image, strings, folder I only see a Settings text, no image.. ? – I only see the ‘3 dots’.png, in Drawable , .But that is from your Recycler Card view ..?

  • Abhi Harsole

    i am not getting drawer list in navigation drawer. error at – adapter = new NavigationDrawerAdapter(getActivity(), getData());

  • Art Agellon

    Tried this the other day and the Fragment Drawer does not show the lists anymore

  • Ibrahim

    HI, thanks. How do i change the color of the items in the app bar [the app name, overflow menu(the 3 vertical dots)] to be white. I followed yours and it was black. I use latest version of android studio 2.3.

  • Alan

    addOnItemTouchListener and onDrawerItemSelected doesn’t call
    which part wrong??

  • Kavitha

    Hi,
    Inside fragment_home.xml ,What is the use to give android:orientation=”vertical” for RelativeLayout?

  • Kavitha

    Hi,
    I have followed all your steps,Created own app for navigation Drawer.If i do frequent launches, Previously selected fragment is show,Home Fragment is not displaying

    * Inside onCreate(),I’m calling displayView(0);

  • Jayson

    Hi, the code cant download..

  • Vijay Gurav

    Hi Ravi,
    Your Tutorials are awesome thanks ,it helps me a lot to learn android.

  • Vijay Gurav

    Hi Ravi,
    How i fix this issue Failure saving state: active Faqs{3831cd8a} has cleared index: -1

  • Kennedy De Vera

    How Can I add icons here in navigation drawer?

    • Justine Lance T. Mojal

      menu.xml, insert drawable name