Friday, January 4, 2013

Android-Context Menu


Generally menus are used to provide extra options for the user in a view.So Context Menu is used in a list view to provide extra options for each row in a list.To have a context menu in your view implement onCreateContextMenu in your activity like this:-

@Override
public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.setHeaderTitle("Menu");
menu.add(0, v.getId(), 0, "Edit");
 menu.add(0, v.getId(), 0, "View");
 menu.add(0, v.getId(), 0, "Delete");
menu.add(0, v.getId(), 0, "Cancel");
}

To open context menu programatically call

openContextMenu(rideListView);

So after selecting an item in context menu you can get control in to this method:-


@Override
public boolean onContextItemSelected(MenuItem item) {

if(item.getTitle()=="Edit") //do some action
else if(item.getTitle()=="View") //do some action
else if(item.getTitle()=="Delete")  //do some action
else if(item.getTitle()=="Cancel")  //do some action
else {return false;}
return true;
}

If you want to close the context menu programatically call

closeContextMenu();

Override oncontextmenuclosed method to do some action after closing menu


@Override
public void onContextMenuClosed(Menu menu) {
// TODO Auto-generated method stub
super.onContextMenuClosed(menu);
}




No comments:

Post a Comment