Tuesday 9 September 2014

Navigation drawer with header in android


Navigation drawer with header in android : 

The navigation drawer is a panel that displays the app’s main navigation options on the left edge of the screen. It is hidden most of the time, but is revealed when the 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.
This lesson describes how to implement a navigation drawer using the DrawerLayout APIs available in the Support Library.

Create a Drawer Layout

To add a navigation drawer, declare your user interface with aDrawerLayout object as the root view of your layout. Inside theDrawerLayout, add one view that contains the main content for the screen (your primary layout when the drawer is hidden) and another view that contains the contents of the navigation drawer.


<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">
<FrameLayout
android:id="@+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<ListView
android:id="@+id/left_drawer"
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>

This layout demonstrates some important layout characteristics:
  • The main content view (the FrameLayout above) must be the first child in the DrawerLayout because the XML order implies z-ordering and the drawer must be on top of the content.
  • The main content view is set to match the parent view's width and height, because it represents the entire UI when the navigation drawer is hidden.
  • The drawer view (the ListView) must specify its horizontal gravity with the android:layout_gravityattribute. To support right-to-left (RTL) languages, specify the value with "start" instead of "left" (so the drawer appears on the right when the layout is RTL).
  • The drawer view specifies its width in dp units and the height matches the parent view. The drawer width should be no more than 320dp so the user can always see a portion of the main content.

Initialize the Drawer List & Drawer Latyout

First,you have to initialize the drawer list and the drawer layout.Then have to set the values for the listview using adapter.

mColors = getResources().getStringArray(R.array.colors_array);
mDrawerLayout=(DrawerLayout)findViewById(R.id.drawer_layout);
mDrawerList=(ListView)findViewById(R.id.left_drawer);

Add Header view 

Inflate the layout into the new view called header.and set the header view into the listview.

header.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >
    <RelativeLayout
        android:id="@+id/RelativeLayout1"
        android:layout_width="match_parent"
        android:layout_height="80dp"
        android:background="@drawable/bg" >
        <TextView
            android:id="@+id/textView1"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_alignParentTop="true"
            android:layout_margin="5dp"
            android:layout_toRightOf="@+id/profile_image"
            android:gravity="center_vertical"
            android:text="velmuruganandroidcoding.blogspot.in"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:textColor="@color/white"
            android:textStyle="bold" />
        <ImageView
            android:id="@+id/profile_image"
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:layout_alignParentLeft="true"
            android:layout_centerVertical="true"
            android:background="@drawable/icon"
            android:layout_margin="5dp"
            android:gravity="center_vertical" />
    </RelativeLayout>
</FrameLayout>


View header=getLayoutInflater().inflate(R.layout.header, null);
ImageView pro=(ImageView)header.findViewById(R.id.profile_image);
pro.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Clicked",                                                                                    Toast.LENGTH_SHORT).show();
}
});
mDrawerList.addHeaderView(header);

Listen for Open and Close Events

To listen for drawer open and close events, call setDrawerListener() on your DrawerLayout and pass it an implementation of DrawerLayout.DrawerListener. This interface provides callbacks for drawer events such as onDrawerOpened() and onDrawerClosed().


mDrawerToggle=new ActionBarDrawerToggle(thismDrawerLayout, R.drawable.ic_drawer, R.string.drawer_open, R.string.drawer_close){
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};

Create Adapter for listview

create model class for get and set values.

private class ItemsModel{
private String itemName;
private int itemImage;
public ItemsModel(String name, int image) {
// TODO Auto-generated constructor stub
this.itemName=name;
this.itemImage=image;

}
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
public int getItemImage() {
return itemImage;
}
public void setItemImage(int itemImage) {
this.itemImage = itemImage;
}

}

create adapter for listview

private class DrawerAdapter extends BaseAdapter{
ArrayList<ItemsModel> itemsmodel;
public DrawerAdapter(ArrayList<ItemsModel> itemModel) {
// TODO Auto-generated constructor stub
this.itemsmodel=itemModel;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return itemsmodel.size();
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return itemsmodel.get(position);
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public View getView(int position, View view, ViewGroup parent) {
// TODO Auto-generated method stub
if (view == null) {
           LayoutInflater mInflater = (LayoutInflater)getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
           view = mInflater.inflate(R.layout.list_adapter, null);
       }
ImageView img=(ImageView)view.findViewById(R.id.img);
TextView name=(TextView)view.findViewById(R.id.name);
name.setText(itemsmodel.get(position).getItemName());
img.setImageResource(itemsmodel.get(position).getItemImage());
return view;
}
}

Add the names and images into the model and set the adapter in the listview.

itemModel.add(new ItemsModel("Black",itemImages.getResourceId(0, -1)));
       itemModel.add(new ItemsModel("Red",itemImages.getResourceId(1, -1)));
        itemModel.add(new ItemsModel("Green",itemImages.getResourceId(2, -1)));
        itemModel.add(new ItemsModel("Blue",itemImages.getResourceId(3, -1)));
        itemModel.add(new ItemsModel("pink",itemImages.getResourceId(4, -1)));
        itemImages.recycle();
        drawerAdapter=new DrawerAdapter(itemModel);
        mDrawerList.setAdapter(drawerAdapter);

Handle Navigation Click Events


When the user selects an item in the drawer's list, the system calls onItemClick() on theOnItemClickListener given to setOnItemClickListener().


public class DrawerItemClickListener implements OnItemClickListener {
@Override
public void onItemClick(AdapterView<?> arg0, View view, int position, long arg3) {
// TODO Auto-generated method stub
if(position != 0){
lastIndex=position;
selectItem(position);
}else{
mDrawerList.setItemChecked(lastIndex, true);
}
}
}
private void selectItem(int position){
Log.d("POS", position+"");
Fragment fragment=new ColorsFragment();
Bundle bundle=new Bundle();
bundle.putInt("Position", position-1);
fragment.setArguments(bundle);
FragmentManager fragmentManager=getFragmentManager();
                 fragmentManager.beginTransaction().replace(R.id.content_frame,                       fragment).commit();
mDrawerList.setItemChecked(position, true);
setTitle(mColors[position-1]);
mDrawerLayout.closeDrawer(mDrawerList);
}

in selectItem() you have to call the related fragment to the give position.Here I have create simple fragment and change the background color and text in depends on the give input.


public class ColorsFragment extends Fragment{
private int[] colors;
private int position;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootview=inflater.inflate(R.layout.fragment_layout, container,false);
position=getArguments().getInt("Position");
RelativeLayout layout=(RelativeLayout)rootview.findViewById(R.id.layout);
TextView textView=(TextView)rootview.findViewById(R.id.textview);
colors=getActivity().getResources().getIntArray(R.array.colors);
textView.setText(getResources().getStringArray(R.array.colors_array)[position]);
layout.setBackgroundColor(colors[position]);
return rootview;
}
}

When using the ActionBarDrawerToggle, you must call it during

onPostCreate() and onConfigurationChanged()


@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);
// Pass any configuration change to the drawer toggls
mDrawerToggle.onConfigurationChanged(newConfig);
}

Screenshot:






DOWNLOAD FULL SOURCE CODE

3 comments:

Unknown said...

Nice tutorial, there is no other tutorial as this much easy to add a header to the navigation drawer.

Admin said...

Hey velmurugan!,
Add syntax highlighter to show your codes more efficient

Music said...

I like to show a web view inside black layout. Can you give the code, please ?.