i assume that you already know:

  • what is a ContextMenu

this post talks about how to use ContextMenu with a ListView. i have just got started with thost by the time of writing this post, and that is all i know about. but it works.

inside my Activity's file List.java:

public class test extends ListActivity {

    public static final int MENU_ITEM_ID_DELETE = 100;
    public static final int MENU_ITEM_ID_RENAME = 200;
    public static final int MENU_ITEM_ORDER_DELETE = 100;
    public static final int MENU_ITEM_ORDER_RENAME = 200;
    public static final int MENU_GROUP_ONLY_ONE = 100;
    private AdapterView.AdapterContextMenuInfo myInfo;
    private ListView lv;
    private String strCaption;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.list); // using my custom layout
        lv = getListView();
        mySetAnAdapterToListViewMethod(); // details to filling a ListView is omitted
        registerForContextMenu(lv);
    }

    public void onCreateContextMenu(ContextMenu menu, View v,
            ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        myInfo = (AdapterView.AdapterContextMenuInfo) menuInfo;
        strCaption = ((TextView) myInfo.targetView).getText().toString();
        menu.setHeaderIcon(R.drawable.myHeaderImage); // using my custom image
        menu.setHeaderTitle(strCaption);
        menu.add(MENU_GROUP_ONLY_ONE, MENU_ITEM_ID_DELETE, MENU_ITEM_ORDER_DELETE, R.string.list_menu_Delete); // using my custom string values
        menu.add(MENU_GROUP_ONLY_ONE, MENU_ITEM_ID_RENAME, MENU_ITEM_ORDER_RENAME, R.string.list_menu_Rename); // using my custom string values
    }

    public boolean onContextItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case MENU_ITEM_ID_DELETE:
            Toast.makeText(getApplicationContext(), "delete attempted", Toast.LENGTH_SHORT).show();
            break;
        case MENU_ITEM_ID_RENAME:
            Toast.makeText(getApplicationContext(), "delete attempted", Toast.LENGTH_SHORT).show();
        }
        return super.onContextItemSelected(item);
    }

    private void mySetAnAdapterToListViewMethod() {
        // a method to fill the list
    }

}

the example says it all. as an alternative method that i am not familiar with, seems that the onCreateContextMenu(...) method could use MenuInflater instead of all those menu.blah() methods. something like this: (uncertain)

MenuInflater inflater=new ...;
inflater.inflate(...);

could be used to replace all the menu.blah methods.

reference