Skip to main content

Slide menu like facebook and Google+ in android

Here is the Example of Slide menu.just copy the code in your project and enjoy:

SlideMenu.java





import java.lang.reflect.Method;
import java.util.ArrayList;

import org.xmlpull.v1.XmlPullParser;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.res.XmlResourceParser;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.animation.Interpolator;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

public class SlideMenu extends LinearLayout {

// keys for saving/restoring instance state
private final static String KEY_MENUSHOWN = "menuWasShown";
private final static String KEY_STATUSBARHEIGHT = "statusBarHeight";
private final static String KEY_SUPERSTATE = "superState";
Button Back;

public static class SlideMenuItem {
public int id;
public Drawable icon;
public String label;
}

// a simple adapter
private static class SlideMenuAdapter extends ArrayAdapter<SlideMenuItem> {
Activity act;
SlideMenuItem[] items;
Typeface itemFont;

class MenuItemHolder {
public TextView label;
public ImageView icon;
}

public SlideMenuAdapter(Activity act, SlideMenuItem[] items, Typeface itemFont) {
super(act, R.id.menu_label, items);
this.act = act;
this.items = items;
this.itemFont = itemFont;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View rowView = convertView;
if (rowView == null) {
LayoutInflater inflater = act.getLayoutInflater();
rowView = inflater.inflate(R.layout.slidemenu_listitem, null);
MenuItemHolder viewHolder = new MenuItemHolder();
viewHolder.label = (TextView) rowView.findViewById(R.id.menu_label);
if(itemFont != null)
viewHolder.label.setTypeface(itemFont);
viewHolder.icon = (ImageView) rowView.findViewById(R.id.menu_icon);
rowView.setTag(viewHolder);
}

MenuItemHolder holder = (MenuItemHolder) rowView.getTag();
String s = items[position].label;
holder.label.setText(s);
holder.icon.setImageDrawable(items[position].icon);

return rowView;
}
}

// this tells whether the menu is currently shown
private boolean menuIsShown = false;
// this just tells whether the menu was ever shown
private boolean menuWasShown = false;
private int statusHeight = -1;
private static View menu;
private static ViewGroup content;
private static FrameLayout parent;
private static int menuSize;
private Activity act;
private Drawable headerImage;
private Typeface font;
private TranslateAnimation slideRightAnim;
private TranslateAnimation slideMenuLeftAnim;
private TranslateAnimation slideContentLeftAnim;

private static ArrayList<SlideMenuItem> menuItemList;
private SlideMenuInterface.OnSlideMenuItemClickListener callback;

/**
* Constructor used by the inflation apparatus.
* To be able to use the SlideMenu, call the {@link #init init()} method.
* @param context
*/
public SlideMenu(Context context) {
super(context);
}

/**
* Constructor used by the inflation apparatus.
* To be able to use the SlideMenu, call the {@link #init init()} method.
* @param attrs
*/
public SlideMenu(Context context, AttributeSet attrs) {
super(context, attrs);
}


/**
* Constructs a SlideMenu with the given menu XML.
* @param act The calling activity.
* @param menuResource Menu resource identifier.
* @param cb Callback to be invoked on menu item click.
* @param slideDuration Slide in/out duration in milliseconds.
*/
public SlideMenu(Activity act, int menuResource, SlideMenuInterface.OnSlideMenuItemClickListener cb, int slideDuration) {
super(act);
init(act, menuResource, cb, slideDuration);
}

/**
* Constructs an empty SlideMenu.
* @param act The calling activity.
* @param cb Callback to be invoked on menu item click.
* @param slideDuration Slide in/out duration in milliseconds.
*/
public SlideMenu(Activity act, SlideMenuInterface.OnSlideMenuItemClickListener cb, int slideDuration) {
this(act, 0, cb, slideDuration);
}

public void init(Activity act, int menuResource, SlideMenuInterface.OnSlideMenuItemClickListener cb, int slideDuration) {

this.act = act;
this.callback = cb;

// set size
menuSize = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 180, act.getResources().getDisplayMetrics());

// create animations accordingly
slideRightAnim = new TranslateAnimation(-menuSize, 0, 0, 0);
slideRightAnim.setFillAfter(true);
slideMenuLeftAnim = new TranslateAnimation(0, -menuSize, 0, 0);
slideMenuLeftAnim.setFillAfter(true);
slideContentLeftAnim = new TranslateAnimation(menuSize, 0, 0, 0);
slideContentLeftAnim.setFillAfter(true);
setAnimationDuration(slideDuration);
// and get our menu
parseXml(menuResource);
}

/**
* Set how long slide animation should be
* @see TranslateAnimation#setDuration(long)
* @param slideDuration
* How long to set the slide animation
*/
public void setAnimationDuration(long slideDuration) {
slideRightAnim.setDuration(slideDuration);
slideMenuLeftAnim.setDuration(slideDuration*3/2);
slideContentLeftAnim.setDuration(slideDuration*3/2);
}

/**
* Set an Interpolator for the slide animation.
* @see TranslateAnimation#setInterpolator(Interpolator)
* @param i
* The {@link Interpolator} object to set.
*/
public void setAnimationInterpolator(Interpolator i) {
slideRightAnim.setInterpolator(i);
slideMenuLeftAnim.setInterpolator(i);
slideContentLeftAnim.setInterpolator(i);
}

/**
* Sets an optional image to be displayed on top of the menu.
* @param d
*/
public void setHeaderImage(Drawable d) {
headerImage = d;
}




/**
* Optionally sets the font for the menu items.
* @param f A font.
*/
public void setFont(Typeface f) {
font = f;
}


/**
* Dynamically adds a menu item.
* @param item
*/
public void addMenuItem(SlideMenuItem item) {
menuItemList.add(item);
}


public void setChildicon(int postion,SlideMenuItem d) {
if(menuItemList.size()>postion)
{
menuItemList.set(postion, d);
}
}
/**
* Empties the SlideMenu.
*/
public void clearMenuItems() {
menuItemList.clear();
}



/**
* Slide the menu in.
*/
public void show() {
this.show(true);
}

/**
* Set the menu to shown status without displaying any slide animation.
*/


public void showBackButton() {
Back.setVisibility(View.VISIBLE);

}
public void setAsShown() {
this.show(false);
}

@SuppressLint("NewApi")
private void show(boolean animate) {

/*
* We have to adopt to status bar height in most cases,
* but not if there is a support actionbar!
*/
try {
Method getSupportActionBar = act.getClass().getMethod("getSupportActionBar", (Class[])null);
Object sab = getSupportActionBar.invoke(act, (Object[])null);
sab.toString(); // check for null

if (android.os.Build.VERSION.SDK_INT >= 11) {
// over api level 11? add the margin
getStatusbarHeight();
}
}
catch(Exception es) {
// there is no support action bar!
getStatusbarHeight();
}

// modify content layout params
try {
content = ((LinearLayout) act.findViewById(android.R.id.content).getParent());
}
catch(ClassCastException e) {
/*
* When there is no title bar (android:theme="@android:style/Theme.NoTitleBar"),
* the android.R.id.content FrameLayout is directly attached to the DecorView,
* without the intermediate LinearLayout that holds the titlebar plus content.
*/
content = (FrameLayout) act.findViewById(android.R.id.content);
}
FrameLayout.LayoutParams parm = new FrameLayout.LayoutParams(-1, -1, 3);
parm.setMargins(menuSize, 0, -menuSize, 0);
content.setLayoutParams(parm);

// animation for smooth slide-out
if(animate)
content.startAnimation(slideRightAnim);

// quirk for sony xperia devices, shouldn't hurt on others
if(Build.VERSION.SDK_INT >= 11 && Build.MANUFACTURER.contains("Sony") && menuWasShown)
content.setX(menuSize);

// add the slide menu to parent
parent = (FrameLayout) content.getParent();

try{
parent
= (FrameLayout) content.getParent();
}catch(ClassCastException e){
/*
* Most probably a LinearLayout, at least on Galaxy S3.
* https://github.com/bk138/LibSlideMenu/issues/12
*/
LinearLayout realParent = (LinearLayout) content.getParent();
parent = new FrameLayout(act);
realParent.addView(parent, 0); // add FrameLayout to real parent of content
realParent.removeView(content); // remove content from real parent
parent.addView(content); // add content to FrameLayout
}

LayoutInflater inflater = (LayoutInflater) act.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
menu = inflater.inflate(R.layout.slidemenu, null);
FrameLayout.LayoutParams lays = new FrameLayout.LayoutParams(-1, -1, 3);
lays.setMargins(0, statusHeight, 0, 0);
menu.setLayoutParams(lays);
parent.addView(menu);

// set header
try {
TextView header = (TextView) act.findViewById(R.id.menu_header);
header.setBackgroundDrawable(headerImage);
}
catch(Exception e) {
// not found
}

// connect the menu's listview
ListView list = (ListView) act.findViewById(R.id.menu_listview);
Back = (Button) act.findViewById(R.id.Back);
Back.setBackgroundResource(R.drawable.btn_back);
SlideMenuItem[] items = menuItemList.toArray(new SlideMenuItem[menuItemList.size()]);
SlideMenuAdapter adap = new SlideMenuAdapter(act, items, font);
list.setAdapter(adap);
list.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

if(callback != null)
callback.onSlideMenuItemClick(menuItemList.get(position).id);

hide();
}
});

Back.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
callback.onBackpressed();
}
});

// slide menu in
if(animate)
menu.startAnimation(slideRightAnim);


menu.findViewById(R.id.overlay).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
SlideMenu.this.hide();
}
});
enableDisableViewGroup(content, false);

menuIsShown = true;
menuWasShown = true;
}



/**
* Slide the menu out.
*/
@SuppressLint("NewApi")
public void hide() {
menu.startAnimation(slideMenuLeftAnim);
parent.removeView(menu);

content.startAnimation(slideContentLeftAnim);

FrameLayout.LayoutParams parm = (FrameLayout.LayoutParams) content.getLayoutParams();
parm.setMargins(0, 0, 0, 0);
content.setLayoutParams(parm);
enableDisableViewGroup(content, true);

// quirk for sony xperia devices, shouldn't hurt on others
if(Build.VERSION.SDK_INT >= 11 && Build.MANUFACTURER.contains("Sony"))
content.setX(0);

menuIsShown = false;
}


private void getStatusbarHeight() {
// Only do this if not already set.
// Especially when called from within onCreate(), this does not return the true values.
if(statusHeight == -1) {
Rect r = new Rect();
Window window = act.getWindow();
window.getDecorView().getWindowVisibleDisplayFrame(r);
statusHeight = r.top;
}
}


//originally: http://stackoverflow.com/questions/5418510/disable-the-touch-events-for-all-the-views
//modified for the needs here
private void enableDisableViewGroup(ViewGroup viewGroup, boolean enabled) {
int childCount = viewGroup.getChildCount();
for (int i = 0; i < childCount; i++) {
View view = viewGroup.getChildAt(i);
if(view.isFocusable())
view.setEnabled(enabled);
if (view instanceof ViewGroup) {
enableDisableViewGroup((ViewGroup) view, enabled);
} else if (view instanceof ListView) {
if(view.isFocusable())
view.setEnabled(enabled);
ListView listView = (ListView) view;
int listChildCount = listView.getChildCount();
for (int j = 0; j < listChildCount; j++) {
if(view.isFocusable())
listView.getChildAt(j).setEnabled(false);
}
}
}
}

// originally: https://github.com/darvds/RibbonMenu
// credit where credits due!
private void parseXml(int menu){

menuItemList = new ArrayList<SlideMenuItem>();

// use 0 id to indicate no menu (as specified in JavaDoc)
if(menu == 0) return;

try{
XmlResourceParser xpp = act.getResources().getXml(menu);

xpp.next();
int eventType = xpp.getEventType();


while(eventType != XmlPullParser.END_DOCUMENT){

if(eventType == XmlPullParser.START_TAG){

String elemName = xpp.getName();

if(elemName.equals("item")){


String textId = xpp.getAttributeValue("http://schemas.android.com/apk/res/android", "title");
String iconId = xpp.getAttributeValue("http://schemas.android.com/apk/res/android", "icon");
String resId = xpp.getAttributeValue("http://schemas.android.com/apk/res/android", "id");

SlideMenuItem item = new SlideMenuItem();
item.id = Integer.valueOf(resId.replace("@", ""));
if (iconId != null) {
item.icon = act.getResources().getDrawable(Integer.valueOf(iconId.replace("@", "")));
}
item.label = resourceIdToString(textId);

menuItemList.add(item);
}

}

eventType = xpp.next();

}


} catch(Exception e){
e.printStackTrace();
}

}



private String resourceIdToString(String text){
if(!text.contains("@")){
return text;
} else {
String id = text.replace("@", "");
return act.getResources().getString(Integer.valueOf(id));

}
}


@Override
protected void onRestoreInstanceState(Parcelable state) {
try{

if (state instanceof Bundle) {
Bundle bundle = (Bundle) state;

statusHeight = bundle.getInt(KEY_STATUSBARHEIGHT);

if(bundle.getBoolean(KEY_MENUSHOWN))
show(false); // show without animation

super.onRestoreInstanceState(bundle.getParcelable(KEY_SUPERSTATE));

return;
}

super.onRestoreInstanceState(state);

}
catch(NullPointerException e) {
// in case the menu was not declared via XML but added from code
}
}



@Override
protected Parcelable onSaveInstanceState() {
Bundle bundle = new Bundle();
bundle.putParcelable(KEY_SUPERSTATE, super.onSaveInstanceState());
bundle.putBoolean(KEY_MENUSHOWN, menuIsShown);
bundle.putInt(KEY_STATUSBARHEIGHT, statusHeight);

return bundle;
}


}
SlideMenuInterface.java

public interface SlideMenuInterface {
interface OnSlideMenuItemClickListener {
public void onSlideMenuItemClick(int itemId);
public void onBackpressed();
}

}

slidemenu.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>

<LinearLayout
android:layout_width="180dip"
android:layout_height="fill_parent"
android:orientation="vertical"
android:background="#3E5CB6"
>

<TextView
android:id="@+id/menu_header"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#ffffffff"
android:textSize="20dip"
android:padding="10dip"
android:gravity="center"
android:textStyle="bold"
android:layout_gravity="center_horizontal"
/>
<Button
android:id="@+id/Back"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone"
android:layout_marginTop="12dip"
android:layout_gravity="center_horizontal"
/>

<ListView
android:id="@+id/menu_listview"
android:layout_marginTop="8dip"
android:layout_width="wrap_content"
android:layout_marginLeft="10dip"
android:layout_marginRight="10dip"
android:background="#20315C"
android:cacheColorHint="#00000000"
android:layout_height="wrap_content"
android:listSelector="@android:color/transparent"
android:divider="@android:color/black"
android:dividerHeight="1dip" />
</LinearLayout>

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

</LinearLayout>


slidemenu_listitem.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >

<ImageView
android:id="@+id/menu_icon"
android:layout_width="35dp"
android:layout_height="35dp"
android:layout_marginTop="35dip"
android:layout_marginLeft="10dip"
android:layout_marginRight="5dip"
android:layout_marginBottom="35dip"
/>

<TextView
android:id="@+id/menu_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="34dip"
android:textSize="16dp"
android:layout_marginLeft="10dip"
android:layout_gravity="center"
android:layout_marginBottom="35dip"
android:textColor="#ffffffff"
/>

</LinearLayout>

activity_main.xml


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >
<!-- here you have to give slidemenu class path with package name"if your package name is "om.example.slide",then here you have to write <com.example.slide.SlideMenu/>" -->
    <com.coboltforge.slidemenu.SlideMenu
        android:id="@+id/slideMenu"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
   
    <Button
        android:id="@+id/buttonMenu"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="Menu" />

</RelativeLayout>

slide.xml


<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >

    <item
        android:id="@+id/item_one"
        android:icon="@drawable/ic_launcher"
        android:title="@string/item_one">
    </item>
    <item
        android:id="@+id/item_two"
        android:icon="@drawable/ic_launcher"
        android:title="@string/item_two">
    </item>
    <item
        android:id="@+id/item_three"
        android:icon="@drawable/ic_launcher"
       
        android:title="@string/item_three">
    </item>
    <item
        android:id="@+id/item_four"
        android:icon="@drawable/ic_launcher"
        android:title="@string/item_four">
    </item>

</menu>


strings.xml

<resources>

    <string name="app_name">SlideMenuExample</string>
    <string name="item_one">Menu Item One</string>
    <string name="item_two">Menu Item Two</string>
    <string name="item_three">Menu Item Three</string>
    <string name="item_four">Menu Item Four</string>
    <string name="menubutton">If you do not happen to have an ActionBar, click here to activate the SlideMenu!</string>

</resources>

MainActivity.java

import com.coboltforge.slidemenu.SlideMenu;
import com.coboltforge.slidemenu.SlideMenu.SlideMenuItem;
import com.coboltforge.slidemenu.SlideMenuInterface.OnSlideMenuItemClickListener;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity implements OnSlideMenuItemClickListener {

private SlideMenu slidemenu;
private final static int MYITEMID = 42;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/*
* There are two ways to add the slide menu:
* From code or to inflate it from XML (then you have to declare it in the activities layout XML)
*/
// this is from code. no XML declaration necessary, but you won't get state restored after rotation.
// slidemenu = new SlideMenu(this, R.menu.slide, this, 333);
// this inflates the menu from XML. open/closed state will be restored after rotation, but you'll have to call init.
slidemenu = (SlideMenu) findViewById(R.id.slideMenu);
slidemenu.init(this, R.menu.slide, this, 333);
// this can set the menu to initially shown instead of hidden
// slidemenu.setAsShown();
// set optional header image
slidemenu.setHeaderImage(getResources().getDrawable(R.drawable.ic_launcher));
// this demonstrates how to dynamically add menu items
SlideMenuItem item = new SlideMenuItem();
item.id = MYITEMID;
item.icon = getResources().getDrawable(R.drawable.left_arrow);
item.label = "Dynamically added item";
//slidemenu.addMenuItem(item);
slidemenu.setChildicon(0, item);
//slidemenu.setChildicon(0,item);
// connect the fallback button in case there is no ActionBar
Button b = (Button) findViewById(R.id.buttonMenu);
b.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
slidemenu.show();
}
});
}


@Override
public void onSlideMenuItemClick(int itemId) {

switch(itemId) {
case R.id.item_one:
// slidemenu.init(this, R.menu.slide2, this, 333);
// SlideMenuItem item = new SlideMenuItem();
// item.id = MYITEMID;
// item.icon = getResources().getDrawable(R.drawable.ic_launcher);
// item.label = "Dynamically added item";
//
// slidemenu.addMenuItem(item);
// slidemenu.notify();
Intent in=new Intent(this,FeatureActivity.class);
startActivity(in);
Toast.makeText(this, "Item one selected", Toast.LENGTH_SHORT).show();
break;
case R.id.item_two:
Toast.makeText(this, "Item two selected", Toast.LENGTH_SHORT).show();
break;
case R.id.item_three:
Toast.makeText(this, "Item three selected", Toast.LENGTH_SHORT).show();
break;
case R.id.item_four:
Toast.makeText(this, "Item four selected", Toast.LENGTH_SHORT).show();
break;
case MYITEMID:
Toast.makeText(this, "Dynamically added item selected", Toast.LENGTH_SHORT).show();
break;
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case android.R.id.home: // this is the app icon of the actionbar
slidemenu.show();
break;
}
return super.onOptionsItemSelected(item);
}


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

AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.slidemenuexample"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
android:minSdkVersion="5"
android:targetSdkVersion="13" />

<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

</manifest>



Comments

Popular posts from this blog

Bitmap scalling and cropping from center

How to Bitmap scalling and cropping from center? public class ScalingUtilities {     /**      * Utility function for decoding an image resource. The decoded bitmap will      * be optimized for further scaling to the requested destination dimensions      * and scaling logic.      *      * @param res      *            The resources object containing the image data      * @param resId      *            The resource id of the image data      * @param dstWidth      *            Width of destination area      * @param dstHeight      *     ...

Custom camera using SurfaceView android with autofocus & auto lights & more

Custom camera using SurfaceView android with autofocus & auto lights & much more /**  * @author Tatyabhau Chavan  *  */ public class Preview extends SurfaceView implements SurfaceHolder.Callback {     private SurfaceHolder mHolder;     private Camera mCamera;     public Camera.Parameters mParameters;     private byte[] mBuffer;     private Activity mActivity;     // this constructor used when requested as an XML resource     public Preview(Context context, AttributeSet attrs) {         super(context, attrs);         init();     }     public Preview(Context context) {         super(context);         init();     }     public Camera getCamera() {        ...

Recycle view adapter in android

Recycle view adapter             The   RecyclerView   widget is a more advanced and flexible version of   ListView . This widget is a container for displaying large data sets that can be scrolled very efficiently by maintaining a limited number of views. Use the   RecyclerView widget when you have data collections whose elements change at runtime based on user action or network events. The   RecyclerView   class simplifies the display and handling of large data sets by providing: ·          Layout managers for positioning items ·          Default animations for common item operations, such as removal or addition of items You also have the flexibility to define custom layout managers and animations for   RecyclerView   widgets. RecyclerViewFragment.class public class RecyclerViewFragment...