Friday, January 25, 2013

Working With Menu: Creating Context Menu In Android

The Android Development Tutorials blog contains Basic as well as Advanced android tutorials.Go to Android Development Tutorials to get list of all Android Tutorials.


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.

Learn Creating Option Menu In Android
Android Custom Alert Dialog Example

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.





Some More Good Android Topics
Customizing Toast In Android
Showing Toast for Longer Time
Customizing Checkboxes In Android
Customizing Progress Bar
To learn Basic of Android Animation go to Android Animation Basics



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 View. Here 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 your onCreateContextMenu() 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 Completye 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;
}
}



}





New Advance Topics:
Android ImageSwitcher Android TextSwitcher Android ViewFlipper
Android Gesture Detector Handling/Detecting Swap Events Gradient Drawable
Detecting Missed Calls Hide Title Bar GridView Animation

Beginning With Android
Android : Introduction Configuring Eclipse for Android Development
Creating Your First Android Project Understanding Android Manifest File of your android app

Advance Android Topics Customizing Android Views


Working With Layouts Working With Views

Understanding Layouts in Android Using Buttons and EditText in Android
Working with Linear Layout (With Example) Using CheckBoxes in Android
Nested Linear Layout (With Example) Using AutoCompleteTextView in Android Grid View
Relative Layout In Android ListView
Table Layout Android ProgressBar
Frame Layout(With Example) Customizing ProgressBar
Absolute Layout Customizing Radio Buttons
Grid Layout Customizing Checkboxes In Android

Android Components Dialogs In Android

Activity In Android Working With Alert Dialog
Activity Life Cycle Adding Radio Buttons In Dialog
Starting Activity For Result Adding Check Boxes In Dialog
Sending Data from One Activity to Other in Android Creating Customized Dialogs in Android
Returning Result from Activity Creating Dialog To Collect User Input
Android : Service DatePicker and TimePickerDialog
BroadcastReceiver Using TimePickerDialog and DatePickerDialog In android

Menus In Android ListView:
Creating Option Menu Populating ListView With DataBase
Creating Context Menu In Android Populating ListView with ArrayList
ListView with Custom Adapter

Toast Working With SMS
Customizing Toast In Android How to Send SMS in Android
Customizing the Display Time of Toast How To Receive SMS
Customizing Toast At Runtime Accessing Inbox In Android
Adding Image in Toast
Showing Toast for Longer Time


TelephonyManager Storage: Storing Data In Android
Using Telephony Manager In Android SharedPreferences In Android
Reading and Writing files to Internal Stoarage
Working With Incoming Calls DataBase
How To Handle Incoming Calls in Android Working With Database in Android
How to Forward an Incoming Call In Android Creating Table In Android
CALL States In Android Inserting, Deleting and Updating Records In Table in Android


Miscellaneous
Notifications In Android
How To Vibrate The Android Phone
Sending Email In Android
Opening a webpage In Browser
How to Access PhoneBook In Android
Prompt User Input with an AlertDialog



17 comments:

  1. i am not able to see setOnItemlongclick() event trigger code in the code..please let me know

    Reply Delete
  2. Thank u very much....... Good Work....... Helped me a lot...... !

    Reply Delete
  3. I really enjoyed reading your article. I found this as an informative and interesting post, so I think it is very useful and knowledgeable. I would like to thank you for the effort you have made in writing this article.

    Reply Delete
  4. Admirando o compromisso que você tem com o seu site
    e as excelentes informações que você oferece!
    Você escreve dados novos que não são as mesmas coisas que vejo em outros
    sites na internet. Fantástica ! Estou adicionando seu feed RSS
    na minha conta do Google.

    Reply Delete
  5. online casino real money
    online casino gambling
    best online casino
    casinos online
    casino games slots

    Reply Delete
  6. This text is worth everyone's attention. When can I find out more?

    Reply Delete
  7. Hi there, just wanted to mention, I liked this post. It was
    inspiring. Keep on posting!

    Reply Delete
  8. http://www.micropromocodes.com Best Place for Upto 80% Off Free Coupon Codes, Promotion Codes,
    Discount Deals and Promo Offers For Online Shopping,Upto 80% Off Promo Coupon Codes.
    Save on Online Shopping Always. Use Coupons.
    Exclusive Coupons · Genuine Offers · Updated Daily · Best Coupons · Free Coupons · Best Offers,
    Types: Coupon Codes, Discount Coupons, Offers & Deals,Save Upto 80% Off on Microsoft Store Promo Code,

    Reply Delete
  9. Hello, i think that i saw you visited my blog so i came to “return the favor”.I'm attempting
    to find things to improve my web site!I suppose its ok to use some of your ideas!!

    Reply Delete
  10. Hey There. I found your blog using msn. This is a very well written article.
    I will be sure to bookmark it and return to read more of your
    useful info. Thanks for the post. I will definitely comeback.

    Reply Delete
  11. Me ha agradado mucho la noticia, realmente buena, muchas gracias por la información, muy
    ilustrativa. Continuo navegando por la pagina a aprender mas cosas informativas, gracias again.

    Reply Delete
  12. I’ve the same problem sometimes, but I generally just force myself via it and revise later. Good luck! soa vest

    Reply Delete
  13. Try unique Style Celebrity
    Taylor Swift Red Coat and Grab More styles

    Reply Delete
  14. Want to get the full breakdown of each player's outfit and where to buy it? Check out the squid game outfit​ for detailed insights and shopping links

    Reply Delete
  15. Whether you need ghostwriting services to start from scratch, book editing services to refine your work, or book proofreading services to perfect every word, I’ve got you covered. My book printing services deliver stunning hard copies, while top-tier book formatting software ensures your eBook is perfectly styled. With our ebook writing service and book marketing services, we’ll make sure your book reaches the audience it deserves. Publishing isn’t just about the final product—it’s about creating something you’re proud to share with the world.

    Reply Delete

Subscribe to: Post Comments (Atom)

AltStyle によって変換されたページ (->オリジナル) /