Search code examples
androidcontextmenuandroid-adapterview

How can I make this ContextMenu Items clickable and add action to items?


I get some information from a database and I created an ArrayAdapter for show this information. If I click on an item a menu appears with four possible action. But I don't know how can I add action listener for this menu items.

     MySQLiteHelper db = new MySQLiteHelper(this);

     List<Client> list = db.getAllClients(); 
     final ListView listview = (ListView) findViewById(R.id.listView_ID);

     final ArrayAdapter adapter = new ArrayAdapter(this,
     android.R.layout.simple_list_item_1, list);
     listview.setAdapter(adapter);

     registerForContextMenu(listview);
}


@Override
public void onCreateContextMenu(ContextMenu menu, View v,   ContextMenu.ContextMenuInfo menuInfo) {
if (v.getId() == R.id.listView_ID) {
    ListView lv = (ListView) v;
    AdapterView.AdapterContextMenuInfo acmi = (AdapterContextMenuInfo) menuInfo;
    Object obj = (Object) lv.getItemAtPosition(acmi.position);

    menu.add("Call");
    menu.add("Email");
    menu.add("Edit");
    menu.add("Delete");

}
}

Solution

  • You can implement onContextItemSelected in the same class as your onCreateContextMenu but you'll need to give your menu items IDs, so replace

    menu.add("Call")
    

    with something like

    menu.add(MenuItem.NONE, CALL_ITEM_ID, MenuItem.NONE, "Call");
    

    (The two NONEs refer to grouping and ordering of items - see http://developer.android.com/reference/android/view/Menu.html#add(int, int, int, java.lang.CharSequence)

    Then you can have

    public boolean onContextItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case CALL_ITEM_ID:
            doCallStuff();
    ...
    

    Alternatively, menu.add() returns a MenuItem, to which you can add an OnMenuItemClickListener, like this:

    MenuItem callItem = menu.add("Call");
    callItem.setOnMenuItemClickListener(new MenuItemOnClickListener() {
        public boolean onMenuItemClick(MenuItem item) {
            // do whatever you want to do... 
            doCallStuff();
            // then return true to say you've handled this
            return true;
        }
    });