Android Material Design Navigation Drawer With Header View

Android Material Design Navigation Drawer With Header View

In this tutorial we are going to learn how to implement android Navigation Drawer with Header View. Some recent android applications have used the Header View in Navigation Drawer like in GMail android application.

I wrote an extensive tutorial on Android Navigation Drawer with Material Design. I will suggest you read the post first because we will focus on the slight difference between the two application projects.

What we have achieved in the first tutorial is to create a Navigation Drawer with a ListView and an event listener is attached to the navigation items. The final result is as shown below.

navieight

The result we want to achieve is to extend what we have already done and to go further to add a Header View in our navigation drawer. The final result will look like the image below.

Android Material Design Navigation Drawer With Header View

You can proceed with creating a new android project or you can download the Android Navigation Drawer with Material Design tutorial source code and import it in your android IDE.

Once you have done setting up the project, the first thing we will add is the CircularImageView dependency library. This will afford us the possibility to convert the profile image we will use in the HeaderView to a circular ImageView.

Open your project build.gradle file and update the dependencies as below

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:21.0.3'
    compile 'de.hdodenhof:circleimageview:1.2.1'
}

In other to add a Header View in the List drawer, we are going to create a layout that we will inflate in other to attach it to our ListView object.

The layout file will contain one circular ImageView and three Text views.

Please make sure to add the Header View to the ListVeiw object using the addHeaderView()  method before calling setAdapter()  method of the ListView class.

The layout file code snippet is as shown. Copy and paste the code on your project.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="200dp"
    android:background="@drawable/header" >

    <de.hdodenhof.circleimageview.CircleImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/imageView"
        android:layout_marginTop="24dp"
        android:layout_centerHorizontal="true"
        android:src="@drawable/face"
        android:id="@+id/circleView"
    />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/profile_name"
        android:id="@+id/profile_name"
        android:layout_below="@+id/circleView"
        android:layout_marginTop="16dp"
        android:textColor="@color/accent_color"
        android:textSize="14sp"
        android:layout_centerHorizontal="true" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/profile_address"
        android:id="@+id/profile_address"
        android:layout_below="@+id/profile_name"
        android:layout_marginTop="16dp"
        android:textColor="@color/black_color"
        android:layout_centerHorizontal="true" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/profile_email"
        android:id="@+id/profile_email"
        android:layout_marginTop="16dp"
        android:textColor="@color/black_color"
        android:layout_below="@+id/profile_address"
        android:layout_centerHorizontal="true" />

</RelativeLayout>

Now that we have done with the layout, we will open the MainActivity.java file and add the following lines of code on it.

LayoutInflater inflater = getLayoutInflater();

View listHeaderView = inflater.inflate(R.layout.header_list,null, false);

mDrawerList.addHeaderView(listHeaderView);

What we have done here is to get a handler for the LayoutInflater. Subsequently we will inflate the header_list.xml layout file and assign it to a View.

Then we will call the addHeaderView() method of the ListView class and we will pass our view handler as a parameter.

The complete code for this class is as shown below.

package inducesmile.com.androidnavigation;

import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

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


public class MainActivity extends ActionBarActivity {

    private DrawerLayout mDrawerLayout;
    private ListView mDrawerList;
    String[]titles = {"Nigeria", "Ghana", "Senegal", "Togo"};
    private CharSequence mTitle;
    private CharSequence mDrawerTitle;
    private ActionBarDrawerToggle mDrawerToggle;
    private Toolbar topToolBar;

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

        mTitle = mDrawerTitle = getTitle();

        topToolBar = (Toolbar)findViewById(R.id.toolbar);
        setSupportActionBar(topToolBar);
        topToolBar.setLogo(R.drawable.logo);
        topToolBar.setLogoDescription(getResources().getString(R.string.logo_desc));

        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerList = (ListView) findViewById(R.id.left_drawer);
        LayoutInflater inflater = getLayoutInflater();
        View listHeaderView = inflater.inflate(R.layout.header_list,null, false);

        mDrawerList.addHeaderView(listHeaderView);

        List<ItemObject> listViewItems = new ArrayList<ItemObject>();
        listViewItems.add(new ItemObject("Nigeria", R.drawable.imageone));
        listViewItems.add(new ItemObject("Ghana", R.drawable.imagetwo));
        listViewItems.add(new ItemObject("Senegal", R.drawable.imagethree));
        listViewItems.add(new ItemObject("Togo", R.drawable.imagefour));

        mDrawerList.setAdapter(new CustomAdapter(this, listViewItems));

        mDrawerToggle = new ActionBarDrawerToggle(MainActivity.this, mDrawerLayout, R.string.drawer_open, R.string.drawer_close) {

            /** Called when a drawer has settled in a completely closed state. */
            public void onDrawerClosed(View view) {
                super.onDrawerClosed(view);
                getSupportActionBar().setTitle(mTitle);
                invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
            }

            /** Called when a drawer has settled in a completely open state. */
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
                getSupportActionBar().setTitle(mDrawerTitle);
                invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
            }
        };

        // Set the drawer toggle as the DrawerListener
        mDrawerLayout.setDrawerListener(mDrawerToggle);
        mDrawerToggle.setDrawerIndicatorEnabled(true);

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);

        mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                // make Toast when click
                Toast.makeText(getApplicationContext(), "Position " + position, Toast.LENGTH_LONG).show();
                selectItemFragment(position);
            }
        });
    }

    private void selectItemFragment(int position){

        Fragment fragment = null;
        FragmentManager fragmentManager = getSupportFragmentManager();
        switch(position) {
            default:
            case 0:
                fragment = new DefaultFragment();
                break;
            case 1:
                fragment = new DefaultFragment();
                break;
            case 2:
                fragment = new DefaultFragment();
                break;
            case 3:
                fragment = new DefaultFragment();
                break;
        }
        fragmentManager.beginTransaction().replace(R.id.main_fragment_container, fragment).commit();

        mDrawerList.setItemChecked(position, true);
        setTitle(titles[position]);
        mDrawerLayout.closeDrawer(mDrawerList);
    }
    @Override
    public void setTitle(CharSequence title) {
        mTitle = title;
        getSupportActionBar().setTitle(mTitle);
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        // Sync the toggle state after onRestoreInstanceState has occurred.
        mDrawerToggle.syncState();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        mDrawerToggle.onConfigurationChanged(newConfig);
    }

    @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 onPrepareOptionsMenu(Menu menu) {
        // If the nav drawer is open, hide action items related to the content view
        boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
        return super.onPrepareOptionsMenu(menu);
    }

    @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 (mDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

Now, when you run your application you will see the interface that looks similar to the sample that was shown earlier on.

You can download the code for this tutorial below. If you are having hard time downloading the tutorials, kindly contact me.

Remember to subscribe with your email so that you will be among the first to receive our new post once it is published

One Response

Add a Comment