Navigation drawer is a UI design pattern that provides a set of menu items when user swipes from left edge of the application to the right. In Android, navigation drawer is available via Android Support library from revision 13 ( May/2013 ) onwards .
A nice Android application where navigation drawer is integrated is YouTube.
In this article, we are going to develop an Android application that contains a navigation drawer.
This application is developed in Eclipse (4.2.1) with ADT plugin (22.0.1) and Android SDK (22.0.1) .
1. Create a new Android application project namely “NavigationDrawerDemo”
2. Configure the application project
3. Design application launcher icon
4. Create a blank activity
5. Enter MainActivity details
6. Add Android Support library to this project
By default, Android support library (android-support-v4.jar ) is added to this project by Eclipse IDE to the directory libs. If it is not added, we can do it manually by doing the following steps :
- Open Project Explorer by Clicking “Window -> Show View -> Project Explorer”
- Right click this project
- Then from popup menu, Click “Android Tools -> Add Support Library “
7. Download and extract the given below file to res/drawable-mdpi
8. Download and extract the given below file to res/drawable-hdpi
9. Download and extract the given below file to res/drawable-xhdpi
10. Update the file res/values/strings.xml
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">NavigationDrawerDemo</string> <string name="action_settings">Settings</string> <string name="hello_world">Hello world!</string> <string-array name="rivers"> <item >Brahmaputra</item> <item >Ganges</item> <item >Kaveri</item> <item >Godavari</item> <item >Periyar</item> <item >Bharathappuzha (Nila)</item> <item >Yamuna</item> </string-array> <string name="drawer_open">Open navigation drawer</string> <string name="drawer_close">Close navigation drawer</string> </resources>
11. Update the layout file res/layout/activity_main.xml
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/drawer_layout" android:layout_width="match_parent" android:layout_height="match_parent"> <!-- The main content view --> <FrameLayout android:id="@+id/content_frame" android:layout_width="match_parent" android:layout_height="match_parent" /> <!-- The navigation drawer --> <ListView android:id="@+id/drawer_list" android:layout_width="240dp" android:layout_height="match_parent" android:layout_gravity="start" android:choiceMode="singleChoice" android:divider="@android:color/transparent" android:dividerHeight="0dp" android:background="#111"/> </android.support.v4.widget.DrawerLayout>
12. Create the layout file res/layout/fragment_layout.xml
<?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="match_parent" android:orientation="vertical" > <TextView android:id="@+id/tv_content" android:layout_width="fill_parent" android:layout_height="fill_parent" android:gravity="center" android:textSize="40sp" /> </LinearLayout>
13. Create the layout file res/layout/drawer_list_item.xml
<TextView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@android:id/text1" android:layout_width="match_parent" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceListItemSmall" android:gravity="center_vertical" android:paddingLeft="16dp" android:paddingRight="16dp" android:textColor="#fff" android:background="?android:attr/activatedBackgroundIndicator" android:minHeight="?android:attr/listPreferredItemHeightSmall"/>
14. Create the fragment class src/in/wptrafficanalyzer/navigationdrawerdemo/RiverFragment.java
package in.wptrafficanalyzer.navigationdrawerdemo; import android.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; public class RiverFragment extends Fragment{ @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Retrieving the currently selected item number int position = getArguments().getInt("position"); // List of rivers String[] rivers = getResources().getStringArray(R.array.rivers); // Creating view correspoding to the fragment View v = inflater.inflate(R.layout.fragment_layout, container, false); // Getting reference to the TextView of the Fragment TextView tv = (TextView) v.findViewById(R.id.tv_content); // Setting currently selected river name in the TextView tv.setText(rivers[position]); // Updating the action bar title getActivity().getActionBar().setTitle(rivers[position]); return v; } }
15. Update the class src/in/wptrafficanalyzer/navigationdrawerdemo/MainActivity.java
package in.wptrafficanalyzer.navigationdrawerdemo; import android.app.Activity; import android.app.FragmentManager; import android.app.FragmentTransaction; import android.os.Bundle; import android.support.v4.app.ActionBarDrawerToggle; import android.support.v4.widget.DrawerLayout; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ArrayAdapter; import android.widget.ListView; public class MainActivity extends Activity { // Within which the entire activity is enclosed DrawerLayout mDrawerLayout; // ListView represents Navigation Drawer ListView mDrawerList; // ActionBarDrawerToggle indicates the presence of Navigation Drawer in the action bar ActionBarDrawerToggle mDrawerToggle; // Title of the action bar String mTitle=""; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mTitle = (String) getTitle(); // Getting reference to the DrawerLayout mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); mDrawerList = (ListView) findViewById(R.id.drawer_list); // Getting reference to the ActionBarDrawerToggle mDrawerToggle = new ActionBarDrawerToggle( this, mDrawerLayout, R.drawable.ic_drawer, R.string.drawer_open, R.string.drawer_close){ /** Called when drawer is closed */ public void onDrawerClosed(View view) { getActionBar().setTitle(mTitle); invalidateOptionsMenu(); } /** Called when a drawer is opened */ public void onDrawerOpened(View drawerView) { getActionBar().setTitle("Select a river"); invalidateOptionsMenu(); } }; // Setting DrawerToggle on DrawerLayout mDrawerLayout.setDrawerListener(mDrawerToggle); // Creating an ArrayAdapter to add items to the listview mDrawerList ArrayAdapter<String> adapter = new ArrayAdapter<String>( getBaseContext(), R.layout.drawer_list_item , getResources().getStringArray(R.array.rivers) ); // Setting the adapter on mDrawerList mDrawerList.setAdapter(adapter); // Enabling Home button getActionBar().setHomeButtonEnabled(true); // Enabling Up navigation getActionBar().setDisplayHomeAsUpEnabled(true); // Setting item click listener for the listview mDrawerList mDrawerList.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // Getting an array of rivers String[] rivers = getResources().getStringArray(R.array.rivers); //Currently selected river mTitle = rivers[position]; // Creating a fragment object RiverFragment rFragment = new RiverFragment(); // Creating a Bundle object Bundle data = new Bundle(); // Setting the index of the currently selected item of mDrawerList data.putInt("position", position); // Setting the position to the fragment rFragment.setArguments(data); // Getting reference to the FragmentManager FragmentManager fragmentManager = getFragmentManager(); // Creating a fragment transaction FragmentTransaction ft = fragmentManager.beginTransaction(); // Adding a fragment to the fragment transaction ft.replace(R.id.content_frame, rFragment); // Committing the transaction ft.commit(); // Closing the drawer mDrawerLayout.closeDrawer(mDrawerList); } }); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); mDrawerToggle.syncState(); } /** Handling the touch event of app icon */ @Override public boolean onOptionsItemSelected(MenuItem item) { if (mDrawerToggle.onOptionsItemSelected(item)) { return true; } return super.onOptionsItemSelected(item); } /** Called whenever we call invalidateOptionsMenu() */ @Override public boolean onPrepareOptionsMenu(Menu menu) { // If the drawer is open, hide action items related to the content view boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList); menu.findItem(R.id.action_settings).setVisible(!drawerOpen); return super.onPrepareOptionsMenu(menu); } @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; } }
16. Update the menu file res/menu/main.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android" > <item android:id="@+id/action_settings" android:orderInCategory="100" android:showAsAction="ifRoom" android:title="@string/action_settings"/> </menu>
17. Screenshots of the running application
18. Download source code
19. Reference
http://developer.android.com/training/implementing-navigation/nav-drawer.html