Using contextmenu with listview in android

To get the item from the ListView item selected refer to ContextMenuInfo object (see last implemented method below). Full solution as follows:

1) register ListView for context menu in ListActivity class

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // ...
    getListView().setAdapter(mAdapter);
    registerForContextMenu(getListView());
}

1a) if you have complex View on your list you might need to enable long click on each list view in Adapter class

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View view = convertView;
    if (view == null) {
        RelativeLayout layout = (RelativeLayout) LayoutInflater.from(mContext).inflate(R.layout.list_item, parent, false);
        itemLayout = layout;
        itemLayout.setLongClickable(true);
    }
    // ...
    return view;
}

2) implement onCreateContextMenu() and onContextItemSelected() in ListActivity class

@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
    super.onCreateContextMenu(menu, v, menuInfo);
    AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
    String title = ((MyItem) mAdapter.getItem(info.position)).getTitle();
    menu.setHeaderTitle(title);

    menu.add(Menu.NONE, MENU_CONTEXT_DELETE_ID, Menu.NONE, DELETE_TEXT);
}

@Override
public boolean onContextItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case MENU_CONTEXT_DELETE_ID:
        AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
        Log.d(TAG, "removing item pos=" + info.position);
        mAdapter.remove(info.position);
        return true;
    default:
        return super.onContextItemSelected(item);
    }
}

Leave a Comment