Showing posts with label implementing menu in android. Show all posts
Showing posts with label implementing menu in android. Show all posts

Monday 3 November 2014

Android Tutorial 39 : How to Create Option Menu In Android

Android Tutorial

Option Menu:

Option Menu is a drop down menu containing   options, and appears when a users clicks on Menu button.
For Ex:
  
                                               

We can create an Option Menu with following :
  1. Create a menu xml
  2. Register the menu in Activity
  3. Write code to Handle the Clicks on menu items

1: Create xml for menu


     Create a new folder named "menu" in res folder (if menu folder is not there in res folder)
     inside this  Menu folder create .xml    file 

here I have created option.xml   xml for the option menu in  above  Image

           <?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
   
     <item android:id="@+id/ChangeColor"
          android:icon="@drawable/setting"
          android:title="Settings"
          />
    <item android:id="@+id/phoneInformation"
          android:icon="@drawable/phone"
          android:title="My Phone Information" />
   
    <item android:id="@+id/callInfo"
          android:icon="@drawable/callinfo"
          android:title="In and Out Call Info" />

   
    <item android:id="@+id/email"
          android:icon="@drawable/mail"
          android:title="Mail to Developer" />
   
 </menu>

android:id
A resource ID that's unique to the item, which allows the application can recognize the item when the user selects it.
android:icon
An image  to use as the item's icon.
android:title
A tittle to show.


2: Register In Activity


Override onCreateOptionMenu   method and inflate the .xml (here options.xml) inside method 

            @Override
                     public boolean onCreateOptionsMenu(Menu menu) {
                            MenuInflater inflater = getMenuInflater();
                            inflater.inflate(R.menu.options, menu);
                            return true;
                     } 


3: Handle Click Events



When the user selects an item from the options menu (including action items in the action bar), the system calls your activity's onOptionsItemSelected() method. This method passes the MenuItem selected. You can identify the item by calling getItemId(), which returns the unique ID for the menu item (defined by the android:id attribute in the menu resource 

 To Handle click events override  onOptionsItemSelected  method


                               @Override
                     public boolean onOptionsItemSelected(MenuItem item) {
                         // Handle item selection
                        
                      
                         switch (item.getItemId()) {
                             case R.id.ChangeColor:
                                                              // write code to execute when clicked on this option
                                                                return true;   


                             case R.id.phoneInformation:
                                                             // write code to execute when clicked on this option
                                                             return true;
                            
                              case R.id.callInfo:
                                                              // write code to execute when clicked on this option
                                                             return true;
                                
                             case R.id.email:
                                                            // write code to execute when clicked on this option
                                                              return true;
                                
                               default:
                                                   return super.onOptionsItemSelected(item);
                         }
                     }


                     

Option Menu Full Source Code


public classMainActivity extends Activity
{
            @Override
        public void onCreate(Bundle savedInstanceState)
        {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.main);
        }


       // Create Option Menu
     @Override
        public boolean onCreateOptionsMenu(Menu menu) 

        {
            MenuInflater inflater = getMenuInflater();
            inflater.inflate(R.menu.options, menu);
            return true;
        }


         // Handle click events
         @Override
          public boolean onOptionsItemSelected(MenuItem item) 

           {
                         // Handle item selection
                        
                      
                         switch (item.getItemId()) {
                             case R.id.ChangeColor:
                                                              // write code to execute when clicked on this option
                                                                return true;   


                             case R.id.phoneInformation:
                                                             // write code to execute when clicked on this option
                                                             return true;
                            
                              case R.id.callInfo:
                                                              // write code to execute when clicked on this option
                                                             return true;
                                
                             case R.id.email:
                                                            // write code to execute when clicked on this option
                                                              return true;
                                
                               default:
                                                   return super.onOptionsItemSelected(item);
                         }
                     }

Sunday 2 November 2014

Android Tutorial 24 : Working With Menu: Creating Context Menu In Android

Context Menu 

A context menu provides actions that affect a specific item or context frame in the UI.
Context Menu appears when user long press on a View like ListView, GridView etc.


For Ex:  Below Is Context menu  registerd with List View
When A User long Press on a contacts he/she gets two option Call and SMS through Context Menu.









Creating a  context menu

To create a context menu:
  1. Register the View to which the context menu should be associated by calling registerForContextMenu() and pass it the ViewHere we have used Context Menu with ListView
  2. Implement the onCreateContextMenu() method in your Activity When the registered view receives a long-click event, the system calls your onCreateContextMenu()method. This is where you define the menu items, usually by inflating a menu resource.

1:  Registering The View(here List View)  for Context menu.


We have to register the ListView for ContextMenu in onCreate  method


@Override
            public void onCreate(Bundle savedInstanceState)
            {
                    super.onCreate(savedInstanceState);
                    setContentView(R.layout.show_contacts);

              
                    listViewSmartContacts=(ListView)findViewById(R.id.listSmartContacts);                    
                    contactListAdapter=new ContactListAdapter(this);
                    listViewSmartContacts.setAdapter(contactListAdapter);

       
                    // Register the ListView  for Context menu
                    registerForContextMenu(listViewSmartContacts);
       }

2: Implement the onCreateContextMenu()


When the registered view receives a long-click event, the system calls youronCreateContextMenu() method. 

             @Override
            public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo)
            {
                    super.onCreateContextMenu(menu, v, menuInfo);
                    menu.setHeaderTitle("Select The Action"); 
                    menu.add(0, v.getId(), 0, "Call"); 
                    menu.add(0, v.getId(), 0, "Send SMS");
    
            } 


MenuInflater allows you to inflate the context menu from a menu resource 

3: Implement onContextItemSelected method



When the user selects a menu item, the system calls this method so you can perform the appropriate action.


             @Override 
            public boolean onContextItemSelected(MenuItem item)
            { 


                        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
                       
                //  
info.position will give the index of selected item
                           intIndexSelected=info.position              
                                if(item.getTitle()=="Call")
                                {
                
                                   // Code to execute when clicked on This Item

                                } 
                                else if(item.getTitle()=="Send SMS")
                                {
                                   

                                  // Code to execute when clicked on This Item                                                        } 
                                else
                                {

                                    return false;
                                } 
                                return true; 
                       
                                   

              } 
             



The Complete Code:


package com.mtracker;

import com.mtracker.R;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;


public class ShowSmartContactsActivity extends Activity
{
  
      
            ListView listViewSmartContacts;
            ContactListAdapter  contactListAdapter;
            //ArrayList<String> numberList;
           
            String number;
           
            public ShowSmartContactsActivity()
            {
                /// numberList=new ArrayList<String>();
           
            }
            @Override
            public void onCreate(Bundle savedInstanceState)
            {
                    super.onCreate(savedInstanceState);
                    setContentView(R.layout.show_contacts);
       
                   
                    LinearLayout layoutContacts=(LinearLayout)findViewById(R.id.layoutSmartContacts);
                    int APILevel=android.os.Build.VERSION.SDK_INT ;
                    if(APILevel>=14)
                    {
                        layoutContacts.setBackgroundResource(R.color.Default);
                    }
                   
                    listViewSmartContacts=(ListView)findViewById(R.id.listSmartContacts);
                    //getList();
                    contactListAdapter=new ContactListAdapter(this);
                    listViewSmartContacts.setAdapter(contactListAdapter);
      
                                      
                   
                    registerForContextMenu(listViewSmartContacts);
            }
           
           
           
           
           
   
           
      
      
           
               
   
            @Override
            public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo)
            {
                    super.onCreateContextMenu(menu, v, menuInfo);
                    menu.setHeaderTitle("Select The Action"); 
                    menu.add(0, v.getId(), 0, "Call"); 
                    menu.add(0, v.getId(), 0, "Send SMS");
    
            }

            @Override 
            public boolean onContextItemSelected(MenuItem item)
            { 


                        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
                        String number;
              
                        try
                        {
                                number=new ContactListAdapter(this).numberList.get(info.position);
                
               
                
                                if(item.getTitle()=="Call")
                                {
                
                
                                        Intent callIntent = new Intent(Intent.ACTION_CALL);
                                        callIntent.setData(Uri.parse("tel:"+number));
                                        startActivity(callIntent);
                
                
                
        

                                } 
                                else if(item.getTitle()=="Send SMS")
                                {
                                        Intent smsIntent = new Intent(Intent.ACTION_VIEW);
                                        smsIntent.setType("vnd.android-dir/mms-sms");
                                        smsIntent.putExtra("address", number);
                                        startActivity(smsIntent);
                    

                                } 
                                else
                                {return false;} 
                                return true; 
                        }
                        catch(Exception e)
                        {
                                return true;
                        }
            } 
           
           
    

Android Tutorial 23 : Working With Menu: Creating Option Menu

Option Menu:
Option Menu is a drop down menu containing   options, and appears when a users clicks on Menu button.
For Ex:
  
                                               

We can create an Option Menu with following :
  1. Create a menu xml
  2. Register the menu in Activity
  3. Write code to Handle the Clicks on menu items

1: Create xml for menu


     Create a new folder named "Menu" in res folder
     inside this  Menu folder create .xml    file 

here I have created option.xml   xml for the option menu in  above  Image

           <?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
   
     <item android:id="@+id/ChangeColor"
          android:icon="@drawable/setting"
          android:title="Settings"
          />
    <item android:id="@+id/phoneInformation"
          android:icon="@drawable/phone"
          android:title="My Phone Information" />
   
    <item android:id="@+id/callInfo"
          android:icon="@drawable/callinfo"
          android:title="In and Out Call Info" />

   
    <item android:id="@+id/email"
          android:icon="@drawable/mail"
          android:title="Mail to Developer" />
   
 </menu>

android:id
A resource ID that's unique to the item, which allows the application can recognize the item when the user selects it.
android:icon
An image  to use as the item's icon.
android:title
A tittle to show.


2: Register In Activity


Override onCreateOptionMenu   method and inflate the .xml (here options.xml) inside method 

            @Override
                     public boolean onCreateOptionsMenu(Menu menu) {
                            MenuInflater inflater = getMenuInflater();
                            inflater.inflate(R.menu.options, menu);
                            return true;
                     } 


3: Handle Click Events



When the user selects an item from the options menu (including action items in the action bar), the system calls your activity's onOptionsItemSelected() method. This method passes the MenuItem selected. You can identify the item by calling getItemId(), which returns the unique ID for the menu item (defined by the android:id attribute in the menu resource 

 To Handle click events override  onOptionsItemSelected  method


                               @Override
                     public boolean onOptionsItemSelected(MenuItem item) {
                         // Handle item selection
                        
                      
                         switch (item.getItemId()) {
                             case R.id.ChangeColor:
                                                              // write code to execute when clicked on this option
                                                                return true;   


                             case R.id.phoneInformation:
                                                             // write code to execute when clicked on this option
                                                             return true;
                            
                              case R.id.callInfo:
                                                              // write code to execute when clicked on this option
                                                             return true;
                                
                             case R.id.email:
                                                            // write code to execute when clicked on this option
                                                              return true;
                                
                               default:
                                                   return super.onOptionsItemSelected(item);
                         }
                     }