Navigation Drawer In Android With Fragments And Material Design Example
Today’s tutorial is Android Navigation Drawer With Fragments And Material Design Example.
Android Navigation Drawer with fragments example guides you to create a sliding navigation menu with recyclerview.
Android Navigation Drawer with fragments tutorial uses fragments for navigation purpose.
You may have seen some application in which, when choose different options from navigation drawer, action bar shows different icons and labels for every particular fragment.
Checkout your whatsapp, they doing exact this thing with tablayout. If you want ti implement this feature with navigation drawer, then learn how to give actionbar/toolbar each fragment of navigation drawer android.
If you are eager to know how to work with nested fragments, then read to implement nested fragment with navigation drawer android.
Visit this for more information about navigation drawer.
First, check the output and then follow all the steps.
Download Source Code For Android Navigation Drawer With Fragments tutorial
[sociallocker] Download DrawerBasicDemonuts [/sociallocker]
Step 1: Create a new project in Android Studio.
Always try to make default activity as empty activity. It will simplify the initial steps of every app.
Step 2: Update build.gradle(Module:app) file
Add below in build.gradle(Module:app) file
1 |
compile 'com.android.support:recyclerview-v7:23.2.1' |
Final code for build.gradle(Module:app)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
apply plugin: 'com.android.application' android { compileSdkVersion 23 buildToolsVersion "23.0.3" defaultConfig { applicationId "com.exampledemo.parsaniahardik.drawerbasicdemonuts" minSdkVersion 16 targetSdkVersion 22 versionCode 1 versionName "1.0" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) testCompile 'junit:junit:4.12' compile 'com.android.support:appcompat-v7:23.4.0' compile 'com.android.support:recyclerview-v7:23.2.1' } |
Step 3: Preparing two fragments
Create two fragments and give them name as “FriendListFragment” and “NotificationFragment.”
Add below code in fragment_friend_list.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<FrameLayout 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="com.exampledemo.parsaniahardik.drawerbasicdemonuts.FriendListFragment"> <!-- TODO: Update blank fragment layout --> <TextView android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:textSize="30sp" android:background="#4aef44" android:textColor="#fff" android:text="Friends List" /> </FrameLayout> |
Add below code in FriendListFragment.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; public class FriendListFragment extends Fragment { public FriendListFragment() { // Required empty public constructor } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_friend_list, container, false); } } |
Copy following source code in fragment_notification.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<FrameLayout 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="com.exampledemo.parsaniahardik.drawerbasicdemonuts.NotificationFragment"> <!-- TODO: Update blank fragment layout --> <TextView android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:textSize="30sp" android:background="@color/colorAccent" android:textColor="#fff" android:text="Notification" /> </FrameLayout> |
Copy following code in NotificationFragment.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; public class NotificationFragment extends Fragment { public NotificationFragment() { // Required empty public constructor } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_notification, container, false); } } |
Step 4: Adding images
Download images and copy them into “drawable” directory.
Step 5: Updating strings.xml and styles.xml
Update string.xml as per below code
1 2 3 4 5 6 7 8 |
<resources> <string name="app_name">DrawerBasicDemonuts</string> <!-- TODO: Remove or change this placeholder text --> <string name="drawer_open">Open</string> <string name="drawer_close">Close</string> <string name="hello_blank_fragment">Hello blank fragment</string> </resources> |
Update styles.xml as following
1 2 3 4 5 6 7 8 9 10 11 12 |
<resources> <!-- Base application theme. --> <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar"> <!-- Customize your theme here. --> <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> |
Step 6: Adding toolbar.xml
Create new layout resource file and give it name as “toolbar.xml”
Copy below source code in it.
1 2 3 4 5 6 7 8 9 10 |
<?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" /> |
Step 7: Creating lv_item.xml file
Make a new layout resource file named “lv_item.xml”
This file is a recyclerview item file. Add below code in it
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:clickable="true"> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/ivicon" android:layout_marginLeft="5dp" android:layout_marginTop="5dp" android:src="@drawable/notification"/> <TextView android:id="@+id/name" android:layout_width="wrap_content" android:layout_height="35dp" android:paddingLeft="10dp" android:paddingTop="7dp" android:text="Noti" android:paddingBottom="10dp" android:textSize="15dp" android:textStyle="bold" /> </LinearLayout> |
Step 8: Creating Model
Create a new Java class named “DrawerModel” and add following code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
public class DrawerModel { private String name; private int image; public int getImage() { return image; } public void setImage(int image) { this.image = image; } public String getName() { return name; } public void setName(String name) { this.name = name; } } |
Step 9: Making Recyclerview Adapter
Create a new Java class named “DrawerAdapter” and paste below code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
import android.content.Context; import android.view.LayoutInflater; import android.support.v7.widget.RecyclerView; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import java.util.ArrayList; public class DrawerAdapter extends RecyclerView.Adapter<DrawerAdapter.ViewHolder> { ArrayList<DrawerModel> arrayList = new ArrayList<>(); private LayoutInflater inflater; private Context context; public DrawerAdapter(Context context, ArrayList<DrawerModel> arrayList) { this.context = context; inflater = LayoutInflater.from(context); this.arrayList = arrayList; } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = inflater.inflate(R.layout.lv_item, parent, false); ViewHolder holder = new ViewHolder(view); return holder; } @Override public void onBindViewHolder(ViewHolder holder, int position) { holder.title.setText(arrayList.get(position).getName()); holder.ivicon.setImageResource(arrayList.get(position).getImage()); } @Override public int getItemCount() { return arrayList.size(); } class ViewHolder extends RecyclerView.ViewHolder { TextView title; ImageView ivicon; public ViewHolder(View itemView) { super(itemView); title = (TextView) itemView.findViewById(R.id.name); ivicon = (ImageView) itemView.findViewById(R.id.ivicon); } } } |
Step 10: Creating DrawerFragment
Make a new fragment named DrawerFragment.
Add below source code in fragment_drawer.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:background="#e45a2c"> <RelativeLayout android:id="@+id/nav_header_container" android:layout_width="match_parent" android:layout_height="150dp" android:layout_alignParentTop="true" android:background="#4fe7ec"> <ImageView android:layout_width="70dp" android:layout_height="70dp" android:src="@mipmap/ic_launcher" android:scaleType="fitCenter" android:layout_centerInParent="true" /> </RelativeLayout> <android.support.v7.widget.RecyclerView android:id="@+id/listview" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="15dp" /> </LinearLayout> |
Add following source code into DrawerFragment.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 |
import android.content.Context; 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.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; public class DrawerFragment extends Fragment { private View view; private ActionBarDrawerToggle mDrawerToggle; private DrawerLayout mDrawerLayout; private DrawerAdapter drawerAdapter; private View containerView; private RecyclerView recyclerView; private String[] names = new String[]{"Friends List", "Notification" }; private int[] images = new int[]{R.drawable.friendlist, R.drawable.notification}; public DrawerFragment() { // Required empty public constructor } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment view = inflater.inflate(R.layout.fragment_drawer, container, false); recyclerView = (RecyclerView) view.findViewById(R.id.listview); drawerAdapter = new DrawerAdapter(getActivity(),populateList()); recyclerView.setAdapter(drawerAdapter); recyclerView.setLayoutManager(new LinearLayoutManager(getActivity())); recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getActivity(), recyclerView, new ClickListener() { @Override public void onClick(View view, int position) { openFragment(position); mDrawerLayout.closeDrawer(containerView); } @Override public void onLongClick(View view, int position) { } })); openFragment(0); return view; } private void openFragment(int position) { switch (position) { case 0: removeAllFragment(new FriendListFragment(), "Friends"); break; case 1: removeAllFragment(new NotificationFragment(), "Notifiaction"); break; default: break; } } public void removeAllFragment(Fragment replaceFragment, String tag) { FragmentManager manager = getActivity().getSupportFragmentManager(); FragmentTransaction ft = manager.beginTransaction(); manager.popBackStackImmediate(null,FragmentManager.POP_BACK_STACK_INCLUSIVE); ft.replace(R.id.container_body, replaceFragment); ft.commitAllowingStateLoss(); } public void setUpDrawer(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(); } }); } private ArrayList<DrawerModel> populateList(){ ArrayList<DrawerModel> list = new ArrayList<>(); for(int i = 0; i < names.length; i++){ DrawerModel drawerModel = new DrawerModel(); drawerModel.setName(names[i]); drawerModel.setImage(images[i]); list.add(drawerModel); } return list; } public interface ClickListener { void onClick(View view, int position); 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) { } } } |
Step 11: Description of DrawerFragment.java
In onCreateView() method, recyclerview is initialized and its onClick() method is implemented.
For recyclerview’s onClick() method implementation, a class named RecycletTouchListener and an interface named ClickListener is defined.
openFragment() method will open fragment. Here, a removeAllFragment() method is used to remove all fragments from back stack and open a fresh new fragment.
setUpDrawer() method will be used in MainActivity.
Step 12: Updating MainActivity
Copy below code into activity_main.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
<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="com.exampledemo.parsaniahardik.drawerbasicdemonuts.DrawerFragment" android:layout_width="260dp" android:layout_height="match_parent" android:layout_gravity="start" app:layout="@layout/fragment_drawer" tools:layout="@layout/fragment_drawer" /> </android.support.v4.widget.DrawerLayout> |
Update MainActivity.java as per following
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
import android.support.v4.widget.DrawerLayout; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.Toolbar; public class MainActivity extends AppCompatActivity { private Toolbar toolbar; private DrawerFragment drawerFragment; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); getSupportActionBar().setDisplayShowHomeEnabled(true); drawerFragment = (DrawerFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer); drawerFragment.setUpDrawer(R.id.fragment_navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout), toolbar); } } |
Kotlin Version
Kotlin version of this tutorial : Navigation Drawer Kotlin Example
The End for Navigation Drawer In Android Studio example.
Comment if you have queries or want to give a review. Thank you 🙂