17
1 Sliding Menu Functionality Overview The slide menu is said to be one of the advanced feature that has been included to increase flexibility and adoptability of an application. Currently many android applications are influenced by the sliding panel .The main purpose of creating sliding panel is to navigate from one window to another window smoothly. Initially various libraries were used to build the sliding menu, but now the android has officially introduced a sliding panel menu which is incorporated with many advanced concepts. To be specific the Android has incorporated the concept of Navigation Drawer. In this module we will learn about how to build a sliding menu using the eclipse IDE. Prerequisites Download required icons that are used in your app. Eclipse IDE Basic knowledge on java coding Creating a sliding menu Below mentioned is the procedure to create a project to include sliding menu to your app, 1. Go to File and select Android Application Project from New. Give a main activity name with .java as extension. Figure 1: Create an Android Application Project.

Sliding Menu Functionality

Embed Size (px)

DESCRIPTION

Android develoermt

Citation preview

Page 1: Sliding Menu Functionality

1

Sliding Menu Functionality

Overview

The slide menu is said to be one of the advanced feature that has been included to

increase flexibility and adoptability of an application. Currently many android

applications are influenced by the sliding panel .The main purpose of creating sliding

panel is to navigate from one window to another window smoothly.

Initially various libraries were used to build the sliding menu, but now the android has

officially introduced a sliding panel menu which is incorporated with many advanced

concepts. To be specific the Android has incorporated the concept of Navigation

Drawer. In this module we will learn about how to build a sliding menu using the

eclipse IDE.

Prerequisites

Download required icons that are used in your app.

Eclipse IDE

Basic knowledge on java coding

Creating a sliding menu

Below mentioned is the procedure to create a project to include sliding menu to your app,

1. Go to File and select Android Application Project from New. Give a main activity

name with .java as extension.

Figure 1: Create an Android Application Project.

Page 2: Sliding Menu Functionality

2

2. On selecting the Android application project the below window appears, enter

the application name and click on Next.

Figure 2: New Android Application window.

3. Enter the application name and click on Next button.

Figure 3: Creation process.

4. Enter Activity name and Layout Name and click on Finish.

Page 3: Sliding Menu Functionality

3

Figure 4: Specify the activity and layout name.

5. In your res folder, select values and at string.xml copy the below mentioned

code,

strings.xml

<?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">Slider Menu</string> <string name="action_settings">Settings</string> <string name="hello_world">Hello world!</string> <string name="drawer_open">Slider Menu Opened</string> <string name="drawer_close">Slider Menu Closed</string> <!-- Nav Drawer Menu Items --> <string-array name="nav_drawer_items"> <item >Profile</item> <item >History</item> <item >Fare calculator</item> <item >Packages</item> <item >Log out</item> </string-array> <array name="nav_drawer_icons"> <item>@drawable/nav_profile</item> <item>@drawable/ub__nav_history</item> <item>@drawable/nav_share</item> <item>@drawable/nav_payment</item>

<item>@drawable/ub__nav_logout</item> <string name="desc_list_item_icon">Item Icon</string> </resources>

Explanation

In the above code we have used navigation drawer to declare all the variables

used at our app. An array called nav_drawer_items is created to fetch the items

Page 4: Sliding Menu Functionality

4

from drawable folder. Also an array called nav_drawer_icons is created to

display the icons on the screen.The desc_list_item_icon is used to display an

error message if any error occurs while uploading an image or icon.

6. At layout page i.e. your activity_main.xml add the below code,

activity_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/frame_container" android:layout_width="match_parent" android:layout_height="match_parent" /> <ListView android:id="@+id/list_slidermenu" android:layout_width="240dp" android:layout_height="match_parent" android:layout_gravity="start" android:choiceMode="singleChoice" android:divider="@color/list_divider" android:dividerHeight="1dp" android:listSelector="@drawable/list_selector" android:background="@color/list_background"/>

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

Explanation

When the user logs into the app the appearance of the page will be in list view

with title and icons. This part of code makes use of user interface element called

DrawerLayout. At this function we design the appearance of the page. If the user

swipes the list respective fragment is displayed. In the above code at

FrameLayout we have used fragments to replace the main content.ListView is

used to list the layout in list.

7. At drawable folder of res, create four new xml layouts and name them as

1. list_item_bg_normal.xml

2. list_item_bg_pressed.xml

3. list_selector.xml

4. counter_bg.xml

Page 5: Sliding Menu Functionality

5

At each layouts created, insert the code given below.

List_item_bg_normal.xml

<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <gradient android:startColor="@color/list_background" android:endColor="@color/list_background" android:angle="90" /> </shape>

List_item_bg_pressed.xml

<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <gradient android:startColor="@color/list_background_pressed" android:endColor="@color/list_background_pressed" android:angle="90" /> </shape>

List_selector.xml

<?xml version="1.0" encoding="utf-8"?>

<selector

xmlns:android="http://schemas.android.com/apk/res/android">

<item android:drawable="@drawable/list_item_bg_normal"

android:state_activated="false"/>

<item android:drawable="@drawable/list_item_bg_pressed"

android:state_pressed="true"/>

<item android:drawable="@drawable/list_item_bg_pressed"

android:state_activated="true"/>

</selector>

Counter_bg.xml

<?xml version="1.0" encoding="utf-8"?>

<shape xmlns:android="http://schemas.android.com/apk/res/android"

android:shape="rectangle" >

<!-- view background color -->

<solid android:color="@color/counter_text_bg" >

</solid>

<!-- If you want to add some padding -->

<paddingandroid:right="3dp"android:left="3dp" >

</padding>

<!-- Here is the corner radius -->

Page 6: Sliding Menu Functionality

6

<corners android:radius="2dp" >

</corners>

</shape>

It is very essential to build a custom listview as we have used three elements i.e. icon,

title and a counter. To achieve this we build custom adapter class which provides

custom layout for individual list item in listview.Prior building the custom adapter, it is

essential to create layout files required for the listview. We already have layout

drawables and we have used three xml files one for normal state, the other for pressed

state and the third for combining both the layouts. Fourth layout is used to obtain round

corner background for counter value.Custom adapter class is created in order to

provide a custom layout for individual list item in the list view.

8. In the layout folder under res , select the drawer_list_item.xml , add the below

code

<?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="48dp"

android:background="@drawable/list_selector">

<ImageView

android:id="@+id/icon"

android:layout_width="25dp"

android:layout_height="wrap_content"

android:layout_alignParentLeft="true"

android:layout_marginLeft="12dp"

android:layout_marginRight="12dp"

android:contentDescription="@string/desc_list_item_icon"

android:src="@drawable/ic_home"

android:layout_centerVertical="true" />

<TextView

android:id="@+id/title"

android:layout_width="wrap_content"

android:layout_height="match_parent"

android:layout_toRightOf="@id/icon"

android:minHeight="?android:attr/listPreferredItemHeightSmall"

android:textAppearance="?android:attr/textAppearanceListItemSmall"

android:textColor="@color/list_item_title"

android:gravity="center_vertical"

android:paddingRight="40dp"/>

<TextView android:id="@+id/counter"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:background="@drawable/counter_bg"

Page 7: Sliding Menu Functionality

7

android:layout_alignParentRight="true"

android:layout_centerVertical="true"

android:layout_marginRight="8dp"

android:textColor="@color/counter_text_color"/>

</RelativeLayout>

Explanation

As we have created the listview with custom layout another layout file has to be created

to define each list row. The above code creates a relative layout which places icons, title

and counter relative to each other. The RelativeLayout function is used to overlap each

fragment with the main page.The first line declares the prolog which contains XML

version number and type of encoding used in the document. In Relative layout we

declare layout_width to match_parent,layout_height to 48dp,background for the

layout is given as @drawable/list_selector.The image is given with @+id/icon

layout_width of image is set to 25dp,layout_height is set to

wrap_content,layout_alignParentLeft is set to true,layout_marginLeft and

layout_marginRight are set to 12dp.To display the content contentDescription is set

to @string/desc_list_item_icon.The src is set to @drawable/ic_home and

layout_centerVertical is set to true. At text view for title id is set to

@+id/icon,layout_width is set to 25dp ,layout_height is set to

wrap_content,layout_alignParentLeft is set to true,layout_marginLeft is set to

12dp,layout_marginRight is set to 12dp,contentDescription is set to

@string/desc_list_item_icon.src is set to @drawable/ic_home and

layout_centerVertical is set to true to get the title at positioned vertically at centre.

9. Now create a new package to keep all the model classes. At the package, create a

new class and name it NavDrawerItem.java. Add the below code,

package info.androidhive.slidingmenu.model;

public class NavDrawerItem

{

private String title;

private int icon;

private String count = "0";

private boolean isCounterVisible = false;

public NavDrawerItem(){}

public NavDrawerItem(String title, int icon)

{

this.title = title;

this.icon = icon;

}

public NavDrawerItem(String title, int icon, boolean isCounterVisible,

String count)

{

Page 8: Sliding Menu Functionality

8

this.title = title;

this.icon = icon;

this.isCounterVisible = isCounterVisible;

this.count = count;

}

public String getTitle()

{

return this.title;

}

public int getIcon()

{

return this.icon;

}

public String getCount()

{

return this.count;

}

public boolean getCounterVisibility()

{

return this.isCounterVisible;

}

public void setTitle(String title)

{

this.title = title;

}

public void setIcon(int icon)

{

this.icon = icon;

}

public void setCount(String count)

{

this.count = count;

}

public void setCounterVisibility(boolean isCounterVisible)

{

this.isCounterVisible = isCounterVisible;

}

}

Explanation

In NavDrawerItem we declare private String title,private int icon,private String

count="0",private booleanisCounterVisible= false.In NavDrawerItem() function

title is assigned to current title and icon is assigned to current icon.The

NavDrawerItem() function consists of title,icon, isCountVisible, count as

paramaters.In this function title is assigned to current title and icon is assigned to

Page 9: Sliding Menu Functionality

9

current icon. At NavDraweritem() function title is assigned current title, icon is

assigned to current icon, isCounterVisible is assigned to current isCounterVisible and

count is assigned to current count.The isCounterVisible function is used to define the

visibility of counter value. It is set to true if you want to show a counter for particular

list item. If you don’t want the counter to be visible you can set it to false.

10. After having all the required files for custom list adapter we create a class named

NavDrawerListAdapter.java under adapter package.

package info.androidhive.slidingmenu.adapter;

import info.androidhive.slidingmenu.R;

import info.androidhive.slidingmenu.model.NavDrawerItem;

import java.util.ArrayList;

import android.app.Activity;

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 NavDrawerListAdapter extends BaseAdapter

{

private Context context;

private ArrayList<NavDrawerItem> navDrawerItems;

public NavDrawerListAdapter(Context context, ArrayList<NavDrawerItem>

navDrawerItems){

this.context = context;

this.navDrawerItems = navDrawerItems;

}

@Override

public int getCount()

Page 10: Sliding Menu Functionality

10

{

return navDrawerItems.size();

}

@Override

public Object getItem(int position)

{

return navDrawerItems.get(position);

}

@Override

public long getItemId(int position)

{

return position;

}

@Override

public View getView(int position, View convertView, ViewGroup parent)

{

if (convertView == null)

{

LayoutInflater mInflater = (LayoutInflater)

context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);

convertView = mInflater.inflate(R.layout.drawer_list_item, null);

}

ImageView imgIcon = (ImageView) convertView.findViewById(R.id.icon);

TextView txtTitle = (TextView) convertView.findViewById(R.id.title);

TextView txtCount = (TextView) convertView.findViewById(R.id.counter);

imgIcon.setImageResource(navDrawerItems.get(position).getIcon());

txtTitle.setText(navDrawerItems.get(position).getTitle());

Page 11: Sliding Menu Functionality

11

if(navDrawerItems.get(position).getCounterVisibility())

{

txtCount.setText(navDrawerItems.get(position).getCount());

}

else

{

txtCount.setVisibility(View.GONE);

}

return convertView;

}

}

Explanation

In the code above we declare slide menu adapter and import few app activities

required for our app.When the user swipes the main page the necessary fragment is

displayed on the main page.In this code we get the fragment from its location and

display it.

11. Open the main activity page and add the following code,

public class MainActivity extends Activity

{

private DrawerLayout mDrawerLayout;

private ListView mDrawerList;

private ActionBarDrawerToggle mDrawerToggle;

private CharSequence mDrawerTitle;

private CharSequence mTitle;

private String[] navMenuTitles;

private TypedArray navMenuIcons;

private ArrayList<NavDrawerItem> navDrawerItems;

private NavDrawerListAdapter adapter;

@Override

protected void onCreate(Bundle savedInstanceState)

{

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

mTitle = mDrawerTitle = getTitle();

navMenuTitles =

getResources().getStringArray(R.array.nav_drawer_items);

navMenuIcons = getResources()

Page 12: Sliding Menu Functionality

12

.obtainTypedArray(R.array.nav_drawer_icons);

mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);

mDrawerList = (ListView) findViewById(R.id.list_slidermenu);

navDrawerItems = new ArrayList<NavDrawerItem>();

navDrawerItems.add(new NavDrawerItem(navMenuTitles[0],

navMenuIcons.getResourceId(0, -1)));

navDrawerItems.add(new NavDrawerItem(navMenuTitles[1],

navMenuIcons.getResourceId(1, -1)));

navDrawerItems.add(new NavDrawerItem(navMenuTitles[2],

navMenuIcons.getResourceId(2, -1)));

navDrawerItems.add(new NavDrawerItem(navMenuTitles[3],

navMenuIcons.getResourceId(3, -1), true, "22"));

navDrawerItems.add(new NavDrawerItem(navMenuTitles[4],

navMenuIcons.getResourceId(4, -1)));

navDrawerItems.add(new NavDrawerItem(navMenuTitles[5],

navMenuIcons.getResourceId(5, -1), true, "50+"));

navMenuIcons.recycle();

adapter = new NavDrawerListAdapter(getApplicationContext(),

navDrawerItems);

mDrawerList.setAdapter(adapter);

getActionBar().setDisplayHomeAsUpEnabled(true);

getActionBar().setHomeButtonEnabled(true);

mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,

R.drawable.ic_drawer, R.string.app_name, - description for accessibility

R.string.app_name // nav drawer close - description for accessibility

)

{

public void onDrawerClosed(View view)

{

getActionBar().setTitle(mTitle);

invalidateOptionsMenu();

}

public void onDrawerOpened(View drawerView)

{

getActionBar().setTitle(mDrawerTitle);

invalidateOptionsMenu();

}

};

mDrawerLayout.setDrawerListener(mDrawerToggle);

if (savedInstanceState == null)

{

displayView(0);

}

}

@Override

Page 13: Sliding Menu Functionality

13

public boolean onCreateOptionsMenu(Menu menu)

{

getMenuInflater().inflate(R.menu.main, menu);

return true;

}

@Override

public boolean onOptionsItemSelected(MenuItem item)

{

if (mDrawerToggle.onOptionsItemSelected(item)) {

return true;

}

switch (item.getItemId())

{

case R.id.action_settings:

return true;

default:

return super.onOptionsItemSelected(item);

}

}

@Override

public boolean onPrepareOptionsMenu(Menu menu)

{

boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);

menu.findItem(R.id.action_settings).setVisible(!drawerOpen);

return super.onPrepareOptionsMenu(menu);

}

@Override

public void setTitle(CharSequence title)

{

mTitle = title;

getActionBar().setTitle(mTitle);

}

@Override

protected void onPostCreate(Bundle savedInstanceState)

{

super.onPostCreate(savedInstanceState);

mDrawerToggle.syncState();

}

@Override

public void onConfigurationChanged(Configuration newConfig)

{

super.onConfigurationChanged(newConfig);

mDrawerToggle.onConfigurationChanged(newConfig);

}

Page 14: Sliding Menu Functionality

14

Explanation In the above code we have declared the variables required, loaded the titles and icons of list items from string.xml,created an adapter and added each list item. Also we have added navigation drawer listener. The private CharSequence mDrawerTitle is used to declare drawer title.The private String[] navMenuTitles, private TypedArray navMenuIcons are used to declare slide menu items.The getResource().getStringArray(R.array.nav_drawer_items) function is used to load slide menu items and assigned to navMenuTitles.The getResources() .obtainTypedArray(R.array.nav_drawer_icons) is assigned to navMenuIcons and used to get icons from resource.The new ArrayList<NavDrawerItem>() is assigned to navDrawerItems and is used to add nav drawer items to array.The navMenuIcons.recycle() is used to recycle the typed array.The new NavDrawerListAdapter(getApplicationContext(),navDrawerItems) is assigned to adapter and called as an object mDrawerList.setAdapter(adapter) to set the nav drawer list adapter.The getActionBar().setDisplayHomeAsUpEnabled(true), getActionBar().setHomeButtonEnabled(true) functions are used to enable the action bar app icon and make it to work as toggle button.

12. Create a class file named HomeFragment.java and add the below code,

package info.androidhive.slidingmenu;

import android.app.Fragment;

import android.os.Bundle;

import android.view.LayoutInflater;

import android.view.View;

import android.view.ViewGroup;

public class HomeFragment extends Fragment

{

public HomeFragment(){}

@Override

public View onCreateView(LayoutInflater inflater, ViewGroup container,

Bundle savedInstanceState)

{

View rootView = inflater.inflate(R.layout.fragment_home, container, false);

return rootView;

}

}

13. Create a layout file and name it as fragment_home.xml and add the below code,

<?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="match_parent">

<TextView

Page 15: Sliding Menu Functionality

15

android:id="@+id/txtLabel"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_centerInParent="true"

android:textSize="16dp"

android:text="Home View"/>

<ImageView android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_below="@id/txtLabel"

android:src="@drawable/ic_home"

android:layout_centerHorizontal="true"

android:layout_marginTop="10dp"/>

</RelativeLayout>

14. In the MainActivity.java add the below code,

public class MainActivity extends Activity

{

..

..

@Override

protected void onCreate(Bundle savedInstanceState) {

..

mDrawerList.setOnItemClickListener(new SlideMenuClickListener());

}

private class SlideMenuClickListener implements

ListView.OnItemClickListener

{

@Override

public void onItemClick(AdapterView<?> parent, View view, int

position,long id)

{

displayView(position);

}

}

private void displayView(int position)

{

Fragment fragment = null;

switch (position)

{

case 0:

fragment = new HomeFragment();

break;

case 1:

fragment = new FindPeopleFragment();

Page 16: Sliding Menu Functionality

16

break;

case 2:

fragment = new PhotosFragment();

break;

case 3:

fragment = new CommunityFragment();

break;

case 4:

fragment = new PagesFragment();

break;

case 5:

fragment = new WhatsHotFragment();

break;

default:

break;

}

if (fragment != null)

{

FragmentManager fragmentManager = getFragmentManager();

fragmentManager.beginTransaction()

.replace(R.id.frame_container, fragment).commit();

mDrawerList.setItemChecked(position, true);

mDrawerList.setSelection(position);

setTitle(navMenuTitles[position]);

mDrawerLayout.closeDrawer(mDrawerList);

}

else

{

Log.e("MainActivity", "Error in creating fragment");

}

}

}

Explanation

When the user selects an item from navigation drawer the above code is used to

display the user the respected view as the main view.We add a list item click

listener and load the respected fragment view in the call back event.

15. Now, run the app you will get the display as shown in below figure,

Page 17: Sliding Menu Functionality

17

Figure 5: Sample page of sliding menu.