android - 从 ContextMenu 获取 ExpandableListView 的选定项

标签 android contextmenu expandablelistview

您好,我在从 ContextMenu 获取 ExpandableListView 项目的 id 时遇到问题,我需要从数据库中删除该条目(我正在使用内容提供程序)。

@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
    menu.add(Menu.NONE, MENU_EDIT, Menu.NONE, "Edit");
    menu.add(Menu.NONE, MENU_REMOVE, Menu.NONE, "Remove");
}

@Override
public boolean onContextItemSelected(MenuItem item) {
    ExpandableListContextMenuInfo info = (ExpandableListContextMenuInfo) menuItem.getMenuInfo();
    switch (item.getItemId()) {
        case MENU_EDIT:
            editEntry(info.id);
            return true;
        case MENU_REMOVE:
            deleteEntry(info.id);
            return true;
        default:
            return super.onContextItemSelected(item);
    }
}

private void deleteEntry(long id) {
    Uri uri = Uri.parse(DatabaseManager.CONTENT_URI + "/" + id);
    getActivity().getContentResolver().delete(uri, null, null);
}

上下文菜单正在显示,但是当我单击“删除”时没有任何反应。你能告诉我我该怎么办吗?

最佳答案

因为 ExpandableListView 有两个级别 - 组和子级 - “ID”很难直接解释。

您需要将 ExpandableListContextMenuInfo 中的信息分解为组位置和子位置。

使用这两个值,您可以从用作 ExpandableListView 数据源的适配器(此处为 this.exandableListAdapter)检索所选项目。适配器的 getChild() 返回的对象可以转换为您最初放入适配器的任何(自定义)类型:

ExpandableListContextMenuInfo info = (ExpandableListContextMenuInfo) menuItem.getMenuInfo();
int groupPos = ExpandableListView.getPackedPositionGroup(info.packedPosition);
int childPos = ExpandableListView.getPackedPositionChild(info.packedPosition);
MyItemClass item =(MyItemClass) this.expandableListAdapter.getChild(groupPos, childPos);

从这个项目中,您应该能够轻松获取数据库中的 ID 或您需要的任何特定信息。

关于android - 从 ContextMenu 获取 ExpandableListView 的选定项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19069256/

相关文章:

java - 无法切换到主窗口内的浏览器窗口。(Selenium Webdriver)

javascript - 火狐扩展 : get click data when context menu

Android ExpandableListView - 处理没有 child 的 parent

android - razor payment giving 找不到合适的付款方式错误

java - 如何从另一个类的 JComboBox 中获取内容

android - vold.fstab 的内容或 dev_mount 行的语法是什么?

java - LoaderCallbacks.onLoadFinished 在 loader 被重新使用并包含数据时不会被调用

qt - Qt程序在右键单击时崩溃

android - 将 Adapter 设置为 ExpendableListView 类型不匹配

android - 如何在抽屉导航中创建下拉菜单(在 Android 中)?