简体   繁体   中英

How to reference selected ListView item from ContextMenu?

I have implemented a Context Action Bar (CAB) in an activity that displays a listview of accounts. Currently, the only option via the CAB is to delete an account. However, when a user long clicks an account and chooses the delete item, I can't figure out how to get reference to the selected Account. Here is the click listener code:

mAccountListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                if (mActionMode != null) {
                    return false;
                } else {
                    // Start the CAB using the ActionMode.Callback already defined
                    mActionMode = startSupportActionMode(mActionModeCallback);
                    // Get name to set as title for action bar
                    Account account = (Account) mAccountAdapter.getItem(position);
                    mActionMode.setTitle(account.getName());
                    mAccountListView.setSelection(position);
                    return true;
                }
            }
        });

And here is the onItemClicked:

// Called when the user selects a contextual menu item
@Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
    switch (item.getItemId()) {
        case R.id.action_delete_account:
            mode.finish(); // Action picked, so close the CAB
            return true;
        default:
            return false;
    }
}

In the second function, above mode.finish() I would like to delete the account from the database, as well as the adapter. However, I can't figure out how to reference it. I have tried:

Account acc = (Account) mAccountListView.getSelectedItem();

But I get a null value for the account. I have also tried using AdapterContextMenuInfo, but I also get a null object when calling item.getInfo() . Have I made a mistake else where? I don't want to resort to storing a static variable that changes each time an item is selected.

You can set the tag on the ActionMode to pass the Account reference.

Later on just use

Account acc = (Account) mode.getTag();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM