Android Navigation Drawer for Sliding Menu / Sidebar by Kapil - Tuesday, December 15, 2015 http://www.androidtutorialpoint.com/material-design/android-navigation-drawer-for-sliding-menusidebar/ YouTube Video In this tutorial we will be covering how to create Navigation Drawer in Android Application. The Android Navigation Drawer is a sliding panel mostly found on the left edge of the Main Screen where you have your app's main navigation menu or options. To reveal it user swipes a finger from the left edge of the screen or, while at the top level of the App, the user touches the App icon in the action bar. It is known by different names such as Android navigation drawer, Android sliding menu, Android swipe menu among others. You can see almost every popular application using navigation drawer menu in their implementation. Consider the navigation drawers as seen in Google Maps and Screen Recorder App as an example. We will be creating a custom android navigation drawer implementation as seen in most of the apps where user is logged in. As in all our blog posts we will be using android studio for the navigation drawer. (adsbygoogle = window.adsbygoogle ).push({); Create a New Project 1. Go to File? New? New Project 2. Enter Application Name, I have used MyNavigationDrawer 3. Enter Company Domain, this is used to uniquely identify your App's package worldwide. 4. Browse the Project Location, by default Projects get stored at home/androidstudioprojects, you can browse to any other location if you want.then click on Next. 5. Select Minimum SDK. I recommend choosing API 15 : Android 4.0.3(IceCreamSandwich), using this API level you can target approximately 94% of the running android devices at the time of this writing.then click on Next. 6. Choose an Activity, as per your requirement.i will use an Empty Activity, since I would be writing most of the code myself.then Click on Next. 1 / 10
7. Choose an Activity Name. Make sure Generate Layout File check box is selected, Otherwise we have to generate it ourselves.then click on Finish.I have left Activity Name as MainActivity. 8. Gradle will configure your project and resolve the dependencies, Once it is complete proceed for next steps. 9. Since we will be using navigation View, include the following the dependencies of your app level build.gradle located at MyNavigationDrawer? app? build.gradle build.gradle compile 'com.android.support:design:23.0.1'</pre> Create Layout For Navigation Drawer 1. Paste the following code in activity_main. located at MyNavigationDrawer? app? src? main? res? layout? activity_main. activity_main. <? version="1.0" encoding="utf-8"?> <android.support.v4.widget.drawerlayout ns:android="http://schemas.android.com/apk/res/android" ns:app="http://schemas.android.com/apk/res-auto" ns:tools="http://schemas.android.com/tools" android:id="@+id/drawer_layout" android:layout_width="match_parent" android:layout_height="match_parent" android:fitssystemwindows="true" tools:opendrawer="start"> <LinearLayout ns:android="http://schemas.android.com/apk/res/android" ns:app="http://schemas.android.com/apk/res-auto" ns:tools="http://schemas.android.com/tools" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" android:fitssystemwindows="true" tools:context=".mainactivity"> <android.support.design.widget.appbarlayout android:layout_height="wrap_content" android:layout_width="match_parent" android:theme="@style/apptheme.appbaroverlay"> <android.support.v7.widget.toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionbarsize" 2 / 10
android:background="?attr/colorprimary" app:popuptheme="@style/apptheme.popupoverlay" /> </android.support.design.widget.appbarlayout> <RelativeLayout android:layout_width="match_parent" android:layout_height="match_parent"> </RelativeLayout> </LinearLayout> <android.support.design.widget.navigationview android:id="@+id/nav_view" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_gravity="start" android:fitssystemwindows="true" app:headerlayout="@layout/nav_header_main" app:menu="@menu/activity_main_drawer" /> </android.support.v4.widget.drawerlayout> 2. Few Points to consider Here The drawer must be the top element and the main content(linear Layout) must be the first child in the DrawerLayout. The main content view must match the parent view's width and height,since it represents the full screen contents when the drawer is closed. 3. We have used a Drawer Layout widget as parent element with a Linear Layout(representing Main Screen ) and a Navigation View (representing the Main Navigation menu). 4. The Linear Layout consist of AppBar which in turn has a toolbar element,the user will click on the toolbar icon to make the navigation Drawer visible. 5. In the Navigation View, we have to define a headerlayout and a menu item. 6. For the headerlayout create a new layout resorce and name it nav_header_main. Add the following code to it. nav_header_main. <? version="1.0" encoding="utf-8"?> <LinearLayout ns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="@dimen/nav_header_height" android:background="@drawable/side_nav_bar" android:paddingbottom="@dimen/activity_vertical_margin" android:paddingleft="@dimen/activity_horizontal_margin" android:paddingright="@dimen/activity_horizontal_margin" android:paddingtop="@dimen/activity_vertical_margin" android:theme="@style/themeoverlay.appcompat.dark" android:orientation="vertical" 3 / 10
android:gravity="bottom"> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:paddingtop="@dimen/nav_header_vertical_spacing" android:src="@drawable/andy" android:id="@+id/imageview" /> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:paddingtop="@dimen/nav_header_vertical_spacing" android:text="andy Point" android:textappearance="@style/textappearance.appcompat.body1" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="andypoint@androidtutorialpoint.com" android:id="@+id/textview" /> </LinearLayout> the code shown above represents the Header of the navigation bar as shown in the figure below Android Navigation Drawer It consists of a background which I have made as gradient explained in the link below Adding Gradient as Background We also have a Image View and 2 text views as marked in the figure. 7. Let's see the code for the navigation menu items.create a new resource file activity_main_drawer. of type menu and add the following code to it, as we can see from the figure above we have added two menu items Preferences and About. activity_main_drawer. <? version="1.0" encoding="utf-8"?> <menu ns:android="http://schemas.android.com/apk/res/android"> <group android:checkablebehavior="single"> <item android:id="@+id/nav_preferences" android:icon="@android:drawable/ic_menu_preferences" android:title="preferences" /> <item android:id="@+id/nav_about" android:icon="@android:drawable/ic_menu_info_details" android:title="about" /> </group> </menu> 4 / 10
8. Since we chose an empty activity, we have to manually create another menu file named main. which we are using oncreatemenuoptions() method in the MainActivity(); Create a new file and insert the following code. menu. <menu ns:android="http://schemas.android.com/apk/res/android" ns:app="http://schemas.android.com/apk/res-auto" ns:tools="http://schemas.android.com/tools" tools:context=".mainactivity"> <item android:id="@+id/action_settings" android:title="@string/action_settings" android:orderincategory="100" app:showasaction="never" /> </menu> This sliding menu using navigation drawer will be visible when the user presses the dot icon on the right side of the screen. Add Drawables 1. We have used some drawable resources for the project, 1st is a gradient pattern file as explained above. Create a New Resource file of type drawables and name it side_nav_bar. Put the following code in it. side_nav_bar. <shape ns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" > <gradient android:startcolor="#fbc800" android:centercolor="#fe8333" android:endcolor="#ff4d4b" android:type="linear" android:angle="135"/> </shape>" 2. We have used two other png files, one for drawer icon and one for the profile picture, you can copy the images from the code by clicking on the Download Now Button add it to the drawables folder. 5 / 10
Update Styles and Strings. files 1. Update the styles. as follows styles. <resources> <!-- Base application theme. --> <style name="apptheme" parent="theme.appcompat.light.darkactionbar"> <!-- Customize your theme here. --> <item name="colorprimary">@color/colorprimary</item> <item name="colorprimarydark">@color/colorprimarydark</item> <item name="coloraccent">@color/coloraccent</item> </style> <style name="apptheme.noactionbar"> <item name="windowactionbar">false</item> <item name="windownotitle">true</item> </style> <style name="apptheme.appbaroverlay" parent="themeoverlay.appcompat.dark.actionbar" /> <style name="apptheme.popupoverlay" parent="themeoverlay.appcompat.light" /> </resources> 2. Update the strings. which we have used in this android navigation drawer example. The file will be located at MyNavigationDrawer -> app -> src -> main -> res -> values -> strings. as follows strings. <resources> <string name="app_name">mynavigationdrawer</string> <string name="navigation_drawer_open">open navigation drawer</string> <string name="navigation_drawer_close">close navigation drawer</string> <string name="action_settings">settings</string> </resources> 3. Update the dimens. located at MyNavigationDrawer -> app -> src -> main -> res -> values -> dimens. as follows dimens. <resources> 6 / 10
<!-- Default screen margins, per the Android Design guidelines. --> <dimen name="nav_header_vertical_spacing">16dp</dimen> <dimen name="nav_header_height">160dp</dimen> <!-- Default screen margins, per the Android Design guidelines. --> <dimen name="activity_horizontal_margin">16dp</dimen> <dimen name="activity_vertical_margin">16dp</dimen> </resources> 4. Update the AndroidManifest. with the following code. AndroidManifest. <? version="1.0" encoding="utf-8"?> <manifest ns:android="http://schemas.android.com/apk/res/android" package="com.androidtutorialpoint.mynavigationdrawer" > <application android:allowbackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsrtl="true" android:theme="@style/apptheme" > <activity android:name=".mainactivity" android:label="@string/app_name" android:theme="@style/apptheme.noactionbar" > <intent-filter> <action android:name="android.intent.action.main" /> <category android:name="android.intent.category.launcher" /> </intent-filter> </activity> </application> </manifest> Please Note that the package name used is in reverse domain name format in order to uniquelly identify your app globally. We have used our own domain name for this android sliding menu tutorial, do Remember to replace your own package name, the main thing to note here is that we have to use android:theme = @style/apptheme.noactionbar, since we are explicitly including an Action Bar in the layout, Otherwise it would get the following error: This Activity already has an action bar supplied by the window decor. Do not request Window.FEATURE_ACTION_BAR and set windowactionbar to false in your theme to use a Toolbar instead. 7 / 10
Add Functionality to the MainActivity 1. Open MainActivity. located at MyNavigationDrawer? app? src? main?? com.androidtutorialpoint.mynavigationdrawer? MainActivity. Although It must have been open by default on creation of project. 2. Add the following code in the oncreate method of MainActivity. MainActivity. Toolbar toolbar = (Toolbar) findviewbyid(r.id.toolbar); setsupportactionbar(toolbar); DrawerLayout drawer = (DrawerLayout) findviewbyid(r.id.drawer_layout); ActionBarDrawerToggle toggle = new ActionBarDrawerToggle( this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); drawer.setdrawerlistener(toggle); toggle.syncstate(); NavigationView navigationview = (NavigationView) findviewbyid(r.id.nav_view); navigationview.setnavigationitemselectedlistener(new NavigationView.OnNavigationItemSelectedListener() { @Override public boolean onnavigationitemselected(menuitem item) { int id = item.getitemid(); if (id == R.id.nav_preferences) { // Handle the preference action else if (id == R.id.nav_about) { // Handle the About action DrawerLayout drawer = (DrawerLayout) findviewbyid(r.id.drawer_layout); drawer.closedrawer(gravitycompat.start); return true; ); 3. In above code we are referencing the layout elements we declared We have created an ActionBarDrawerToggle object which ties together the functionality of DrawerLayout and the framework ActionBar to implement the recommended design for navigation drawers. toggle.syncstate() is used to to synchronize the indicator with the state of the linked DrawerLayout navigationview.setnavigationitemselectedlistener is used to handle the events when user clicks on one of the navigation items. 8 / 10
4. Next we override the onbackpressed() method so that If the navigation drawer is open, it is closed. Otherwise default implemention of the onbackpressed() works. Add the following code after oncreate() method inside the MainActivity. @Override public void onbackpressed() { DrawerLayout drawer = (DrawerLayout) findviewbyid(r.id.drawer_layout); if (drawer.isdraweropen(gravitycompat.start)) { drawer.closedrawer(gravitycompat.start); else { super.onbackpressed(); 5. Since we started out with an empty activity mention oncreateoptionsmenu() and onoptionselectedmenu() on our own.so paste the below code after onbackpressed() method inside the MainActivity. @Override public boolean oncreateoptionsmenu(menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getmenuinflater().inflate(r.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.. int id = item.getitemid(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; return super.onoptionsitemselected(item); Run this app on your phone and see if the Navigation Drawer is working properly.please comment in case you have any doubts or suggestions. 9 / 10
Powered by TCPDF (www.tcpdf.org) Android Navigation Drawer for Sliding Menu / Sidebar - 12-15-2015 (adsbygoogle = window.adsbygoogle ).push({); What's Next You can experiment with different options or make your custom menu as per your requirement. You can try to integrate Google Login in your app, and once the user is logged in you can show his profile in the navigation drawer. For more details how to Add Google Login to your Android App Refer the following link. Adding Google Login To Android App Similarly you can add Facebook Login to your Android App and show user profile in the navigation drawer. Please refer to the following link to learn how to Add Facebook Login to Your Android Application. Adding Facebook Login To Android App Soon We will be covering how to create android application with Facebook and Google Sign-In, on successful Sign-In the user profile will be shown in the navigation drawer. Till then stay tuned for more tutorials.. and Don't forget to subscribe our blog for latest android tutorials. Also do Like our Facebook Page or Add us on Twitter. PDF generated by Kalin's PDF Creation Station 10 / 10