71

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;
}
Raj
  • 22,346
  • 14
  • 99
  • 142
Eriz
  • 972
  • 2
  • 10
  • 20

7 Answers7

119

First you need to register your context menu on list view.

lv = (ListView) findViewById(R.id.list_view);
registerForContextMenu(lv);

Then, just override activity methods.

/**
 * MENU
 */

@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
      super.onCreateContextMenu(menu, v, menuInfo);
      if (v.getId()==R.id.list_view) {
          MenuInflater inflater = getMenuInflater();
          inflater.inflate(R.menu.menu_list, menu);
      }
}

@Override
public boolean onContextItemSelected(MenuItem item) {
      AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
      switch(item.getItemId()) {
         case R.id.add:
         // add stuff here
            return true;
          case R.id.edit:
            // edit stuff here
                return true;
          case R.id.delete:
        // remove stuff here
                return true;
          default:
                return super.onContextItemSelected(item);
      }
}

Here is an example of menu_list.xml file (you have to put the file in the res/menu folder).

<?xml version="1.0" encoding="utf-8"?>
<menu
  xmlns:android="http://schemas.android.com/apk/res/android">

       <item android:id="@+id/add"
              android:icon="@android:drawable/ic_menu_add"
              android:title="@string/menu_add" />

      <item android:id="@+id/edit"
              android:icon="@android:drawable/ic_menu_edit"
              android:title="@string/menu_edit" />

       <item android:id="@+id/delete"
            android:icon="@android:drawable/my_icon_delete"
             android:title="@string/menu_delete" />

</menu>

Hope it will help.

Sharikov Vladislav
  • 7,049
  • 9
  • 50
  • 87
Zhar
  • 3,330
  • 2
  • 24
  • 25
  • Thanks, it works, but how do I know which item in the list was longclicked ? Any ID? – Enriqe Jan 15 '14 at 12:22
  • 17
    OK, I found it. You can get ID or POSITION of the list item which was longclicked like this: `((AdapterView.AdapterContextMenuInfo)menuInfo).id` `((AdapterView.AdapterContextMenuInfo)menuInfo).position` – Enriqe Jan 15 '14 at 12:33
  • switch statement no longer works as values such as R.id.add are no longer generated as constants. Hence I needed to replace switch with if-else stmt! – mvsagar May 29 '14 at 09:19
  • 3
    Great example but icons are not supported in context menus – dave Apr 16 '15 at 11:57
  • 1
    Hey, you did set up icons for menu, but there are no icons in menu. Why? How I can show icons? – Sharikov Vladislav Jun 22 '15 at 23:13
  • I tried in in my dialogfragment, context menus were shown but `onContextItemSelected` not being called after click on menu item. Why? I use Android 6.0 – Taufik Nur Rahmanda Aug 16 '18 at 06:42
51

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,

7bluephoenix
  • 958
  • 7
  • 18
6

Another approach:

//Deleted individual cart items
    //on list view cell long press
    cartItemList.setOnItemLongClickListener (new OnItemLongClickListener() {
          @SuppressWarnings("rawtypes")
        public boolean onItemLongClick(AdapterView parent, View view, final int position, long id) {
              final CharSequence[] items = { "Delete" };

                AlertDialog.Builder builder = new AlertDialog.Builder(context);

                builder.setTitle("Action:");
                builder.setItems(items, new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog, int item) {
                        cart = cartList.get(position);
                        db.removeProductFromCart(context, cart);

                        new AlertDialog.Builder(context)
                        .setTitle(getString(R.string.success))
                        .setMessage(getString(R.string.item_removed))
                        .setPositiveButton("Done", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) { 
                                Intent intent = new Intent(CartDetailsActivity.this, HomeScreen.class);
                                startActivity(intent);
                            }
                         })
                         .show();

                    }

                });

                AlertDialog alert = builder.create();

                alert.show();
            //do your stuff here
              return false;
          }
        });
TharakaNirmana
  • 10,237
  • 8
  • 50
  • 69
2

You can call Activity.openOptionsMenu() in your click item method

check here
http://developer.android.com/reference/android/app/Activity.html#openOptionsMenu%28%29

Michael Shrestha
  • 2,547
  • 19
  • 30
  • If you can use the options menu - this a nice solution (1 line!) and alternative to doing all the setup needed for a contextMenu off the activity – Gene Bo Mar 12 '14 at 21:14
1

**

after register your context menu on list view

** override onCreateContextMenu Method like this

@Override
    public void onCreateContextMenu(ContextMenu menu,View v, ContextMenu.ContextMenuInfo menuInfo){
        if (v.getId() == R.id.listView){
            AdapterView.AdapterContextMenuInfo info =(AdapterView.AdapterContextMenuInfo)menuInfo;
            MenuItem mnu1=menu.add(0,0,0,"Delete");
            MenuItem mnu2=menu.add(0,1,1,"Share");
        }
    }

then coding for each item that can be selected

 @Override
    public boolean onContextItemSelected(MenuItem menuItem){
        AdapterView.AdapterContextMenuInfo info=(AdapterView.AdapterContextMenuInfo)menuItem.getMenuInfo();
        switch (menuItem.getItemId()) {
            case 0:
                Toast.makeText(this, "Delete Selected", Toast.LENGTH_LONG).show();
                break;
            case 1:
                Toast.makeText(this, "Share Selected", Toast.LENGTH_LONG).show();
                break;

            default:
                break;

        }
        return true;
    }
0

Use registerForContextMenu(); to link context menu to any View successor.

To access to selected ListItem data, simple use the AdapterView.AdapterContextMenuInfo. E.g.:

@Override
public boolean onContextItemSelected(MenuItem item) {
    AdapterView.AdapterContextMenuInfo menuinfo = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
    long selectid = menuinfo.id; //_id from database in this case
    int selectpos = menuinfo.position; //position in the adapter
    switch (item.getItemId()) {
    case 1:
        doSomething(selectid);
    break;
    case 2:
        doSomethingElse(selectpos);
    }
    return super.onContextItemSelected(item);
}
Serge
  • 9
  • 1
0

A quick note for those still struggling, there're two methods

registerForContextMenu(list);
unregisterForContextMenu(list);

Make sure you pick the first.

Saif Hakeem
  • 875
  • 8
  • 9