androidlistviewmenulong-click

creating a menu after a long click event on a list view


I have a list view connected to a database, showing a all the entries. I want a menu to show up if the user long clicks a item in the listview(database entry), showing options to edit or delete the entry. how can i do this.

Till now, I have tried using a onItemLongClick listener and a toast in it showing the id of the view long clicked.

@Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
        int position, long id) {

    String res = Long.toString(id);
     Toast toast = Toast.makeText(this, res, Toast.LENGTH_SHORT);
     toast.show();

    return true;
}

Solution

  • Instead of using onItemLongClick you can use

    public void onCreateContextMenu(final ContextMenu menu, 
                        final View v, final ContextMenuInfo menuInfo) {
     ...
    }
    

    where you setup the options for edit and delete or whatever you need to.

    The actions for the item selected from the context menu can be processed in

    public boolean onContextItemSelected(final MenuItem item)
    

    For more information on context menu see here.

    For a step by step tutorial visit here.

    Edit The second link is broken as it was quite old. But I guess you can refer one of the other highly voted answer to see all the steps involved,