【问题标题】:How to reference selected ListView item from ContextMenu?如何从 ContextMenu 引用选定的 ListView 项目?
【发布时间】:2015-04-08 04:25:39
【问题描述】:

我在显示帐户列表视图的活动中实现了上下文操作栏 (CAB)。目前,通过 CAB 的唯一选择是删除帐户。但是,当用户长按帐户并选择删除项时,我不知道如何获取对所选帐户的引用。这是点击监听代码:

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;
                }
            }
        });

这里是 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;
    }
}

在第二个函数中,上面mode.finish() 我想从数据库中删除帐户,以及适配器。但是,我不知道如何引用它。我试过了:

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

但我得到了该帐户的空值。我也尝试过使用 AdapterContextMenuInfo,但在调用 item.getInfo() 时我也得到了一个空对象。我在其他地方犯错了吗?我不想求助于存储每次选择项目时都会更改的静态变量。

【问题讨论】:

    标签: android listview android-contextmenu


    【解决方案1】:

    您可以在 ActionMode 上set the tag 传递 Account 引用。

    以后就用

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

    【讨论】:

    • 哇,谢谢。我在找到的任何示例中都没有看到这一点,并且在文档中忽略了它。正如我所期望的那样工作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多