简体   繁体   English

如何从ContextMenu引用选定的ListView项目?

[英]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. 我在显示帐户列表视图的活动中实现了上下文操作栏(CAB)。 Currently, the only option via the CAB is to delete an account. 当前,通过CAB的唯一选择是删除帐户。 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: 这是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. 在第二个函数中,在mode.finish()以上,我想从数据库以及适配器中删除帐户。 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() . 我也尝试使用AdapterContextMenuInfo,但在调用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. 您可以在ActionMode上设置标记以传递帐户参考。

Later on just use 以后就用

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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