Tuesday, 5 October 2010

Android: Context menu in ListView after clicking

 

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)

7 comments:

  1. Thank you! it helped me on this

    ReplyDelete
  2. usefull!

    "Ps: I found one disadvantage of this method, you can't use icons in this context menu"

    menu.setHeaderIcon();
    menu.setHeaderTitle("HOLA");

    ReplyDelete
  3. hi can u give me a sample on how to add constructor for delete button.

    ReplyDelete
  4. Thanks!

    You can't use icons? How about:
    menu.add(Menu.NONE, CONTEXT_MENU_UPDATE, Menu.NONE,"update").setIcon()

    ReplyDelete
  5. Thanks so much! This really helped me!!

    ReplyDelete