1. Overwrite the activity's Oncreatecontenxtmenu () method, and call the menu's Add method (MenuItem).
2. Override the activity's oncontextitemselected () method to respond to the Click event of the context menu item.
3. Call the Registerforcontextmenu () method to register the context menu for the view.
Java code:
PackageEOE.local.contextMenu;
importandroid.app.ListActivity;
Importandroid.os.Bundle;
Importandroid.view.ContextMenu;
Importandroid.view.Menu;
Importandroid.view.MenuItem;
Importandroid.view.ContextMenu.ContextMenuInfo;
Importandroid.view.View;
Importandroid.widget.AdapterView.AdapterContextMenuInfo;
Importandroid.widget.ArrayAdapter;
Importandroid.util.Log;
publicclassmainactivityextendslistactivity{
Privatestaticfinalintitem1=menu.first;
privatestaticfinalintitem2=menu.first+1;
privatestaticfinalintitem3=menu.first+2;
/**calledwhentheactivityisfirstcreated.*/
@Override
public void OnCreate (bundlesavedinstancestate) {
Super.oncreate (savedinstancestate);
Showlistview ();
Register ContextMenu for all the item in the ListView
Registerforcontextmenu (Getlistview ());
The Registerforcontextmenu () here can also be replaced with the following statement
Getlistview (). Setoncreatecontextmenulistener (this);
}
Privatevoidshowlistview () {
string[]mstring=newstring[]{
"Lu Fei-monkeydluffy",
"Nami-nami",
"Merman-zoro",
"Shan-sanji",
"Nicol Robin-ms.allsunday",
"Usopp-usoppu",
"Tonitoni Choba-tonytonychopper",
};
Arrayadapter<string>mla=newarrayadapter<string> (Mainactivity.this,
r.layout.main,mstring);
MainActivity.this.setListAdapter (MLA);
}
Context menu, which activates the context menu by long-pressing entries
@Override
Publicvoidoncreatecontextmenu (Contextmenumenu,viewview,
Contextmenuinfomenuinfo) {
Menu.setheadertitle ("character profile");
Add Menu item
Menu.add (0,item1,0, "special features");
Menu.add (0,item2,0, "combat effectiveness");
Menu.add (0,item3,0, "classic Quotations");
}
Menu click Response
@Override
Publicbooleanoncontextitemselected (MenuItem Item) {
Gets the information for the currently selected menu item
Adaptercontextmenuinfo info= (Adaptercontextmenuinfo) item.getmenuinfo ();
LOG.I ("Braincol", String.valueof (info.id));
Switch (Item.getitemid ()) {
CaseITEM1:
Add the processing code here
Break
CaseITEM2:
Add the processing code here
Break
CaseITEM3:
Add the processing code here
Break
}
Returntrue;
}
}
Main.xml Layout file:
<?xmlversion= "1.0" encoding= "Utf-8"?>
<textviewxmlns:android= "Http://schemas.android.com/apk/res/android"
Android:id= "@+id/mytextview"
Android:textsize= "20SP"
Android:layout_width= "Fill_parent"
android:layout_height= "Fill_parent"
android:text= "@string/hello"
/>
Android context Menu Implementation