How to make side menu in android ?

1 comment
Navigation drawer is a UI design pattern that provides a set of menu items when user swipes from left edge of the application to the right. In Android, navigation drawer is available via Android Support library from revision 13 ( May/2013 ) onwards .
A nice Android application where navigation drawer is integrated is YouTube.
In this article, we are going to develop an Android application that contains a navigation drawer.
This application is developed in Android Studio with ADT plug-in (22.0.1) and Android SDK (22.0.1) .

Here I can show you how to use it in your android application.

First of all update your res/values/string.xml to below code.


<?xml version="1.0" encoding="utf-8"?><resources>
    <string name="app_name">NavigationDrawerDemo</string>    <string name="action_settings">Settings</string>    <string name="hello_world">Hello world!</string>    <string-array name="names">        <item >Jitesh</item>        <item >Kush</item>        <item >Devang</item>        <item >Ronak</item>        <item >Jackk</item>        <item >Ravi</item>        <item >Divyang</item>    </string-array>    <string name="drawer_open">Open navigation drawer</string>    <string name="drawer_close">Close navigation drawer</string>

</resources>

After updating the string.xml now it’s time to design some ui for our application.
Update your res/layout/activity_main file to below code.
<android.support.v4.widget.DrawerLayout
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <!-- The main content view -->
    <FrameLayout
        android:id="@+id/content_frame"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
    <!-- The navigation drawer -->
    <ListView android:id="@+id/drawer_list"
        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>
Create the layout file res/layout/fragment_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/tv_content"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:gravity="center"
        android:textSize="40sp" />


</LinearLayout>
Now lets start with some coding for our design .
src/com/jackk/navigationdrawerdemo/NameFragment.java
    android:id="@android:id/text1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceListItemSmall"
    android:gravity="center_vertical"
    android:paddingLeft="16dp"
    android:paddingRight="16dp"
    android:textColor="#fff"
    android:background="?android:attr/activatedBackgroundIndicator"

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


Now lets start with some coding for our design .
src/com/jackk/navigationdrawerdemo/NameFragment.java
package com.jackk.navigationdrawerdemo;
import android.app.Fragment;import android.os.Bundle;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.TextView;
public class NameFragment extends Fragment{
    @Override    public View onCreateView(LayoutInflater inflater, ViewGroup container,        Bundle savedInstanceState) {
        // Retrieving the currently selected item number        int position = getArguments().getInt("position");
        // List of rivers        String[] rivers = getResources().getStringArray(R.array.rivers);
        // Creating view correspoding to the fragment        View v = inflater.inflate(R.layout.fragment_layout, container, false);
        // Getting reference to the TextView of the Fragment        TextView tv = (TextView) v.findViewById(R.id.tv_content);
        // Setting currently selected river name in the TextView        tv.setText(rivers[position]);
        // Updating the action bar title        getActivity().getActionBar().setTitle(rivers[position]);
        return v;    }}


Now Update the class src/in com/jackk/navigationdrawerdemo /MainActivity.java

import android.app.Activity;import android.app.FragmentManager;import android.app.FragmentTransaction;import android.os.Bundle;import android.support.v4.app.ActionBarDrawerToggle;import android.support.v4.widget.DrawerLayout;import android.view.Menu;import android.view.MenuItem;import android.view.View;import android.widget.AdapterView;import android.widget.AdapterView.OnItemClickListener;import android.widget.ArrayAdapter;import android.widget.ListView;
public class MainActivity extends Activity {
    // Within which the entire activity is enclosed    DrawerLayout mDrawerLayout;
    // ListView represents Navigation Drawer    ListView mDrawerList;
    // ActionBarDrawerToggle indicates the presence of Navigation Drawer in the action bar    ActionBarDrawerToggle mDrawerToggle;
    // Title of the action bar    String mTitle="";
    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);
        mTitle = (String) getTitle();
        // Getting reference to the DrawerLayout        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerList = (ListView) findViewById(R.id.drawer_list);
        // Getting reference to the ActionBarDrawerToggle        mDrawerToggle = new ActionBarDrawerToggle( this,            mDrawerLayout,            R.drawable.ic_drawer,            R.string.drawer_open,            R.string.drawer_close){
                /** Called when drawer is closed */                public void onDrawerClosed(View view) {                    getActionBar().setTitle(mTitle);                    invalidateOptionsMenu();                }
                /** Called when a drawer is opened */                public void onDrawerOpened(View drawerView) {                    getActionBar().setTitle("Select a river");                    invalidateOptionsMenu();                }        };
        // Setting DrawerToggle on DrawerLayout        mDrawerLayout.setDrawerListener(mDrawerToggle);
        // Creating an ArrayAdapter to add items to the listview mDrawerList        ArrayAdapter<String> adapter = new ArrayAdapter<String>(            getBaseContext(),            R.layout.drawer_list_item ,            getResources().getStringArray(R.array.rivers)        );
        // Setting the adapter on mDrawerList        mDrawerList.setAdapter(adapter);
        // Enabling Home button        getActionBar().setHomeButtonEnabled(true);
        // Enabling Up navigation        getActionBar().setDisplayHomeAsUpEnabled(true);
        // Setting item click listener for the listview mDrawerList        mDrawerList.setOnItemClickListener(new OnItemClickListener() {            @Override            public void onItemClick(AdapterView<?> parent,                View view,                int position,                long id) {
                    // Getting an array of rivers                    String[] rivers = getResources().getStringArray(R.array.rivers);
                    //Currently selected river                    mTitle = rivers[position];
                    // Creating a fragment object                    NameFragment rFragment = new NameFragment();
                    // Creating a Bundle object                    Bundle data = new Bundle();
                    // Setting the index of the currently selected item of mDrawerList                    data.putInt("position", position);
                    // Setting the position to the fragment                    rFragment.setArguments(data);
                    // Getting reference to the FragmentManager                    FragmentManager fragmentManager = getFragmentManager();
                    // Creating a fragment transaction                    FragmentTransaction ft = fragmentManager.beginTransaction();
                    // Adding a fragment to the fragment transaction                    ft.replace(R.id.content_frame, rFragment);
                    // Committing the transaction                    ft.commit();
                    // Closing the drawer                    mDrawerLayout.closeDrawer(mDrawerList);            }        });    }
    @Override    protected void onPostCreate(Bundle savedInstanceState) {        super.onPostCreate(savedInstanceState);        mDrawerToggle.syncState();    }
    /** Handling the touch event of app icon */    @Override    public boolean onOptionsItemSelected(MenuItem item) {        if (mDrawerToggle.onOptionsItemSelected(item)) {            return true;        }        return super.onOptionsItemSelected(item);    }
    /** Called whenever we call invalidateOptionsMenu() */    @Override    public boolean onPrepareOptionsMenu(Menu menu) {        // If the drawer is open, hide action items related to the content view        boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
        menu.findItem(R.id.action_settings).setVisible(!drawerOpen);        return super.onPrepareOptionsMenu(menu);    }
    @Override    public boolean onCreateOptionsMenu(Menu menu) {        // Inflate the menu; this adds items to the action bar if it is present.        getMenuInflater().inflate(R.menu.main, menu);        return true;    }
}

 Output Snapshots:






1 comment:

  1. please fix code display, its hard to follow.

    ReplyDelete