Saturday, 4 January 2014

Android : Facebook like Drawer Slider layout using ActionBarSherlock Supportive Library


Welcome Guys !!!

Most of the application users of android are fascinated with the layout the application uses. The more attractive and ease-to-use layout the application will have, it will affect the downloads on Play Store in same fashion.
Today i am going to write an article about a most popular kind of layout Android Developers are using.
This layout is recently used my many big applications like Facebook , Google Play Store.
I am going to build a simple application that will have a basic demonstration of the layout.

Before starting you will need a external support library for ActionBar. This will enable to use actionbar for lower version of android.
the support library can be downloaded form GitHub or I have uploaded it on mediafire .. i am going to give you the link for it :
                                            Download ActionBarSherlock
Download it and unzip it on desktop :
Now you need to import this library into your workspace :

for importing : 
Click File -> Import -> Expand General -> Select existing android project into workspace -> Browse for the unzipped file -> (Note) Cheak the copy to workspace cheakbox -> Click ok -> clean the Project

Create a new project and include this as a supporting library. To add this as a supporting library try following steps:
Project -> Right click -> properties -> Android -> add -> Select actionbarsherlock -> OK



The basic look up of the application layout  that we are going to develop is  :


Now it is all set .... let work with some development logic.

The classes would be listed here with proper comment. If the source code  of the application is need ... it will be provided by email .... 

Mail Me at : ajayjaiswalhi@gmail.com

MainActivity.java

import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;


import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.Fragment;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.support.v4.view.GravityCompat;
public class MainActivity extends SherlockFragmentActivity {
// Declare Variable
    DrawerLayout mDrawerLayout;
    ListView mDrawerList;
    ActionBarDrawerToggle mDrawerToggle;
    MenuListAdapter mMenuAdapter;
    String[] title;
    String[] subtitle;
    int[] icon;
    Fragment fragment1 = new Fragment1();
    Fragment fragment2 = new Fragment2();
    Fragment fragment3 = new Fragment3();
    Fragment fragment4 = new Fragment4();
    Fragment fragment5 = new Fragment5();
    AlertDialog alertDialog=null;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.drawer_main);

        // Generate title
        title = new String[] { "Preface", "About Us",
                "Comtemporary Quiz", "About Author", "Reading Material","Key Notes" };

        // Generate subtitle
        subtitle = new String[] { "What this book is about ??", "Who we are ??",
                "Cheak what we learned ??","Behind the book ??","Learn and smile !!" ,"Zip something new !!",};

        // Generate icon
        icon = new int[] { R.drawable.action_about, R.drawable.action_settings,
                R.drawable.collections_cloud, R.drawable.about_author, R.drawable.book, R.drawable.key_notes };

        // Locate DrawerLayout in drawer_main.xml
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);

        // Locate ListView in drawer_main.xml
        mDrawerList = (ListView) findViewById(R.id.left_drawer);

        // Set a custom shadow that overlays the main content when the drawer
        // opens
        mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow,
                GravityCompat.START);

        // Pass results to MenuListAdapter Class
        mMenuAdapter = new MenuListAdapter(this, title, subtitle, icon);

        // Set the MenuListAdapter to the ListView
        mDrawerList.setAdapter(mMenuAdapter);

        // Capture button clicks on side menu
        mDrawerList.setOnItemClickListener(new DrawerItemClickListener());

        // Enable ActionBar app icon to behave as action to toggle nav drawer
        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#662523")));
        // ActionBarDrawerToggle ties together the the proper interactions
        // between the sliding drawer and the action bar app icon
        mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
                R.drawable.ic_drawer, R.string.drawer_open,
                R.string.drawer_close) {

            public void onDrawerClosed(View view) {
                // TODO Auto-generated method stub
                super.onDrawerClosed(view);
            }

            public void onDrawerOpened(View drawerView) {
                // TODO Auto-generated method stub
                super.onDrawerOpened(drawerView);
            }
        };

        mDrawerLayout.setDrawerListener(mDrawerToggle);

        if (savedInstanceState == null) {
            selectItem(0);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getSupportMenuInflater().inflate(R.menu.main, menu);
       return true;
   
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        if (item.getItemId() == android.R.id.home) {

            if (mDrawerLayout.isDrawerOpen(mDrawerList)) {
                mDrawerLayout.closeDrawer(mDrawerList);
            } else {
                mDrawerLayout.openDrawer(mDrawerList);
            }
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
this.finish();
}

@Override
public void onBackPressed() {
// TODO Auto-generated method stub

AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MainActivity.this);

// set title
alertDialogBuilder.setTitle("Exit Application");

alertDialogBuilder
.setMessage(" Do you want to exit ?? ")
.setCancelable(true)
.setPositiveButton("Exit", new DialogInterface.OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
MainActivity.this.finish();


}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int which) {
alertDialog.dismiss();
}
});
// create alert dialog
alertDialog = alertDialogBuilder.create();
alertDialog.show();
// set dialog message


}

// The click listener for ListView in the navigation drawer
    private class DrawerItemClickListener implements
            ListView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                long id) {
            selectItem(position);
        }
    }

    private void selectItem(int position) {

        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        // Locate Position
        switch (position) {
        case 0:
            ft.replace(R.id.content_frame, fragment4);
            break;
        case 1:
            ft.replace(R.id.content_frame, fragment2);
            break;
        case 2:
            ft.replace(R.id.content_frame, fragment3);
            break;
        case 3:
            ft.replace(R.id.content_frame, fragment1);
            break;
        case 4:
            ft.replace(R.id.content_frame, fragment5);
            break;
        case 5:
            ft.replace(R.id.content_frame, fragment5);
            break;
        }
        ft.commit();
        mDrawerList.setItemChecked(position, true);
        // Close drawer
        mDrawerLayout.closeDrawer(mDrawerList);
    }

    @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 toggles
        mDrawerToggle.onConfigurationChanged(newConfig);
    }

}


===========================================================

Create 5 fragment java classes corresponding to every fragment that will be loaded

Fargment1.java

import com.actionbarsherlock.app.SherlockFragment;
import android.os.Bundle;
import android.text.Html;
import android.text.method.ScrollingMovementMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
 
public class Fragment1 extends SherlockFragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment1, container, false);
        String htmlAsAString="<html>" +
        "<body>" +
                       "Hello World !!"
        "</body>"+
        "</html>";
        TextView description=(TextView) rootView.findViewById(R.id.authordescription);
        description.setText(Html.fromHtml(htmlAsAString));
        TextView author=(TextView) rootView.findViewById(R.id.welcomeauthor);
        author.setText(Html.fromHtml("<b><u>About the Author</u></b>"));
        description.setMovementMethod(new ScrollingMovementMethod());
        return rootView;
    }
 
}



=======================================================
Create an xml for the MainActivity.java :

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

   

</RelativeLayout>



=======================================================

Create XML Layouts corresponding to each and every fragment 

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" 
    android:background="#A33421"
   >
    
    <!-- GUI Code goes here -->

</RelativeLayout>

=========================================================

Create a layout that will hold the list for the sidemenu drawer (drawer_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" >

    <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:background="#802220"
        android:choiceMode="singleChoice"
        android:divider="@android:color/transparent"
        android:dividerHeight="0dp" />

</android.support.v4.widget.DrawerLayout>


===============================================================

Create a layout to flat each and every item of the darwer that is going to be slided over (drawer_list_item.xml) :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    style="?attr/spinnerDropDownItemStyle"
    android:layout_width="match_parent"
    android:layout_height="?attr/dropdownListPreferredItemHeight"
    android:orientation="horizontal" >

    <ImageView
        android:id="@+id/icon"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:adjustViewBounds="true" />

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:gravity="center_vertical|left"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/title"
            style="?attr/spinnerDropDownItemStyle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:ellipsize="end"
            android:singleLine="true" />

        <TextView
            android:id="@+id/subtitle"
            style="?attr/spinnerDropDownItemStyle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:ellipsize="end"
            android:singleLine="true"
            android:textAppearance="?attr/textAppearanceSmall" />
    </LinearLayout>

</LinearLayout>

================================================================

Create a MenuListAdapter.java class to inflat the drawer with the layouts created above. This adapter will populate the items in the sidemenu drawers :

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class MenuListAdapter extends BaseAdapter {

    // Declare Variables
    Context context;
    String[] mTitle;
    String[] mSubTitle;
    int[] mIcon;
    LayoutInflater inflater;

    public MenuListAdapter(Context context, String[] title, String[] subtitle,
            int[] icon) {
        this.context = context;
        this.mTitle = title;
        this.mSubTitle = subtitle;
        this.mIcon = icon;
    }

    @Override
    public int getCount() {
        return mTitle.length;
    }

    @Override
    public Object getItem(int position) {
        return mTitle[position];
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        // Declare Variables
        TextView txtTitle;
        TextView txtSubTitle;
        ImageView imgIcon;

        inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View itemView = inflater.inflate(R.layout.drawer_list_item, parent,
                false);

        // Locate the TextViews in drawer_list_item.xml
        txtTitle = (TextView) itemView.findViewById(R.id.title);
        txtSubTitle = (TextView) itemView.findViewById(R.id.subtitle);

        // Locate the ImageView in drawer_list_item.xml
        imgIcon = (ImageView) itemView.findViewById(R.id.icon);

        // Set the results into TextViews
        txtTitle.setText(mTitle[position]);
        txtSubTitle.setText(mSubTitle[position]);

        // Set the results into ImageView
        imgIcon.setImageResource(mIcon[position]);

        return itemView;
    }

}


===================================================

All set... all Go ... !! 
Compile and run the application .

In case you have any problem write me a mail at : ajayjaiswalhi@gmail.com
or you can post your problem at the facebook page : https://www.facebook.com/codegeekstuffs


Thank you !!




No comments:

Post a Comment