Skip to main content

Android Sliding Menu using Navigation Drawer(Only Activity)

In this tutorial we’ll implement a Navigation Drawer using only Activity in our android application. Android navigation drawer is a sliding menu and it’s an important UI component.

Android Navigation Drawer

Android Navigation Drawer is a sliding left menu that is used to display the important links in the application. Navigation drawer makes it easy to navigate between those links. It’s not visible by default and it needs to opened either by sliding from left or clicking its icon in the ActionBar.

In broader terms, Navigation Drawer is an overlay panel, which is a replacement of an activity screen which was specifically dedicated to show all the options and links in the application.


Example

This sample will explain how to do a Navigation Drawer using only Activities

To implement the Navigation Drawer we first need to add android.support.v4.widget.DrawerLayout as the root of the activity layout as shown below.

navigation_drawer.xml
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    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">
        <android.support.design.widget.AppBarLayout
            android:id="@+id/idToolBar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:theme="@style/AppTheme.AppBarOverlay">

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:background="@color/colorPrimary"
                app:popupTheme="@style/AppTheme.PopupOverlay" />

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

        <FrameLayout
            android:id="@+id/content_frame"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

    </LinearLayout>
    <!--Second child layout-->
    <android.support.design.widget.NavigationView
        android:id="@+id/navigation_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:background="@color/colorPrimary"
        app:itemBackground="@drawable/drawer_item_bg"
        app:headerLayout="@layout/nav_drawer_header"
        app:itemTextColor="@color/white"
        app:menu="@menu/menu_item">

    </android.support.design.widget.NavigationView>
</android.support.v4.widget.DrawerLayout>
FrameLayout

FrameLayout is the place where an activity has been placed

Create menu directory in res - 

menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <group android:checkableBehavior="single">
        <item
            android:id="@+id/id_home"
            android:title="Home" />
        <item
            android:id="@+id/id_profile"
            android:title="Profile" />
        <item
            android:id="@+id/id_review"
            android:title="Review"/>
        <item
            android:id="@+id/id_testimonal"
            android:title="Testimonals"/>
        <item
            android:id="@+id/id_subscription"
            android:title="Subscription"/>
        <item
            android:id="@+id/id_logout"
            android:title="Logout"/>
  </group>
</menu>
nav_drawer_header.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="150dp"
    android:orientation="vertical"
    android:background="@color/white">

    <RelativeLayout
        android:id="@+id/headerRelativeLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="horizontal"
            android:weightSum="3.5">

            <LinearLayout
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1">

                <ImageView
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:src="@drawable/app_icon"/>

            </LinearLayout>

            <LinearLayout
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="2.5"
                android:orientation="vertical"
                android:gravity="center">

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:textStyle="bold"
                    android:textColor="@color/colorPrimary"
                    android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium"
                    android:text="MrBrown"/>

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:textAppearance="@style/Base.TextAppearance.AppCompat.Small"
                    android:textColor="@color/colorPrimary"
                    android:text="@string/blog"/>

            </LinearLayout>
        </LinearLayout>
    </RelativeLayout>
</LinearLayout>
In drawable,
nav_drawer_header.xml
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="rectangle" >
            <solid android:color="@color/colorPrimary" />
        </shape>
    </item>
    <item android:top="-2dp" android:right="-2dp" android:left="-2dp">
        <shape>
            <solid android:color="@color/colorPrimary" />
            <stroke
                android:width="1dp"
                android:color="@color/white" />
        </shape>
    </item>
</layer-list>
Add the themes in your styles.xml
<resources>
    <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>
        <item name="drawerArrowStyle">@style/DrawerArrowStyle</item>
        <item name="titleTextColor">@android:color/white</item>
    </style>

    <style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Light" />

    <style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />

    <style name="DrawerArrowStyle" parent="Widget.AppCompat.DrawerArrowToggle">
        <item name="spinBars">true</item>
        <item name="color">@android:color/white</item>
    </style>
</resources>
NavigationActivity.java
public class NavigationActivity extends AppCompatActivity {

    public DrawerLayout drawerLayout;
    ActionBarDrawerToggle actionBarDrawerToggle;
    Toolbar toolbar;
    NavigationView navigationView;

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

        navigationView = (NavigationView) findViewById(R.id.navigation_view);
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.drawer_open, R.string.drawer_closed);
        drawerLayout.setDrawerListener(actionBarDrawerToggle);

        navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(MenuItem item) {
                Intent anIntent;
                switch (item.getItemId()) {
                    case R.id.id_home:
                        anIntent = new Intent(getApplicationContext(), HomeActivity.class);
                        overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
                        finish();
                        startActivity(anIntent);
                        drawerLayout.closeDrawers();
                        break;
//do the same for remaining activity
                                                     }
                return false;
            }
        });
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);

        actionBarDrawerToggle.syncState();
    }
}
HomeActivity.java
public class HomeActivity extends NavigationActivity {

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

        getSupportActionBar().setTitle(Constant.setactionbar_title("HOME"));
        LayoutInflater mInflater = (LayoutInflater) this.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
        View convertView = mInflater.inflate(R.layout.activity_home, null);
        drawerLayout.addView(convertView, 0);
    }
}
where, drawerLayout.addView(convertView, 0); is to add the activity view to drawer layout

Create your own activity_home.xml 

Now the simple Navigation Drawer has created for your application.

_______________________________________________________________________________________
Source code for NavigationDrawer.zip

Happy Coding...

Comments

Popular posts from this blog

Get Phone Number from Contact List - Android Tutorial

When you create an application to send sms or an application to make calls, getting a destination number from the contacts list is a common task. In this Android tip, I am going to show the code to fetch a number from the contacts list. Now let me tell you how to achieve the goal. First, you need to create an Intent object for the PICK_ACTION action. To open the contacts list, the table that contains the contacts information must be specified as a parameter of the constructor of the Intent class. You can refer to the table using ContactsContract.Contacts.CONTENT_URI. Then call the startActivityForResult () method passing the Intent object and request code to open the contacts list. After a contact is selected from the contacts list, to get the result, you need to override the onActivityResult(int reqCode, int resultCode, Intent data) method of the activity. You can call the getData() method of the data parameter to get the table or uri that contains the selected contact. From the t

Spinner with Search on DropDown - Android Tutorial

If you have more values on Dropdown of Spinner its hard to select the last item by making a long scroll. To overcome this issue Android introduced a component called  AutoCompleteTextView Yes it is!!! Then why Spinner with Search? There may be some requirement even though gave much knowledge about it. There is a simple and good library that helps us to achieve this -  SearchableSpinner Gradle dependencies {     ...     implementation 'com.toptoche.searchablespinner:searchablespinnerlibrary:1.3.1' } Usage Now replace your Normal Android Spinner on XML with the following < com.toptoche.searchablespinnerlibrary.SearchableSpinner     android:id="@+id/id_city"     android:layout_width="match_parent"     android:layout_height="wrap_content"     android:background="@android:color/transparent"     android:padding="5dp" /> ___________________________________________________________

Set Focus on Spinner when select Item on Vertical Scroll - Android Tutorial

We may face an issue on Spinner lies on long vertical scroll, (i.e.) when selected and item from dropdown the focus moves to top of scroll. To avoid this please follow this piece of code spinner.setFocusableInTouchMode( true ); spinner.setOnFocusChangeListener( new View.OnFocusChangeListener() {     @Override     public void onFocusChange(View v, boolean hasFocus) {         if (hasFocus) {             if (spinner.getWindowToken() != null ) {                 spinner.performClick();             }         }     } });   _______________________________________________________________________________ Happy Coding...