Search code examples
androidcontextual-action-bar

Passing id of ListView item to ActionMode.Callback object


So my problem right now is that right now I am long clicking an item in a ListView which brings up a contextual action bar. The id passed into onItemLongClick is the variable that I would like to use in the mActionModeCallback's on ActionItemClicked() method. This seems like it would be a fairly common procedure since if a user is editing a list of items, you would want to access the id of that row in the database somehow when the user clicked an "edit" or a "delete" action.

listView.setOnItemLongClickListener(new OnItemLongClickListener() {
    public boolean onItemLongClick(AdapterView<?> p, View view, int pos, long id) {

        //The id of the row in the database
        long variableThatIWantToPassToCallback = id; 
        mActionMode = getActivity().startActionMode(mActionModeCallback);
        view.setSelected(true);
        return true;
    }
});

private ActionMode.Callback mActionModeCallback = new ActionMode.Callback() {

    public boolean onCreateActionMode(ActionMode mode, Menu menu) {}

    public boolean onPrepareActionMode(ActionMode mode, Menu menu) {}

    public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
        //I would like access to the id of the clicked item here, NOT item.getItemId()
    }

    public void onDestroyActionMode(ActionMode mode) {}
};

Solution

  • The proper way to do this is to call mActionMode.setTag("1") in onItemCheckedStateChanged and then from the onActionItemClicked function call mode.getTag();