The easiest way) to create context menu
1)Firs of all you should create ListView maybe with some adapter, so main class should extends ListActivity
2) To register our menu, use:
registerForContextMenu(getListView());3) Then override
final int CONTEXT_MENU_DELETE_ITEM =1; final int CONTEXT_MENU_UPDATE =2; @Override public void onCreateContextMenu(ContextMenu menu, View v,ContextMenu.ContextMenuInfo menuInfo) { menu.add(Menu.NONE, CONTEXT_MENU_DELETE_ITEM, Menu.NONE, "Delete"); menu.add(Menu.NONE, CONTEXT_MENU_UPDATE, Menu.NONE, "update"); }4)Now we should handle click events of our context menu
@Override public boolean onContextItemSelected(MenuItem item) { AdapterView.AdapterContextMenuInfo info= (AdapterView.AdapterContextMenuInfo) item.getMenuInfo(); Long id = getListAdapter().getItemId(info.position);/*what item was selected is ListView*/ switch (item.getItemId()) { case CONTEXT_MENU_DELETE_ITEM: //do smth return(true); case CONTEXT_MENU_UPDATE: //do smth else) return(true); } return(super.onOptionsItemSelected(item)); }
Ps: I found one disadvantage of this method, you can't use icons in this context menu
Books:
Professional Android 4 Application Development (Wrox Professional Guides)
Thank you! it helped me on this
ReplyDeleteThanks
ReplyDeleteTHanks a lot!!
ReplyDeleteusefull!
ReplyDelete"Ps: I found one disadvantage of this method, you can't use icons in this context menu"
menu.setHeaderIcon();
menu.setHeaderTitle("HOLA");
hi can u give me a sample on how to add constructor for delete button.
ReplyDeleteThanks!
ReplyDeleteYou can't use icons? How about:
menu.add(Menu.NONE, CONTEXT_MENU_UPDATE, Menu.NONE,"update").setIcon()
Thanks so much! This really helped me!!
ReplyDelete