【问题标题】:Getting ExpandableListView's selected item from ContextMenu从 ContextMenu 获取 ExpandableListView 的选定项
【发布时间】:2013-09-28 16:42:41
【问题描述】:

您好,我从 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);
}

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

【问题讨论】:

  • 您没有看到从ListView 或/和提供程序中删除的项目?当您触发delete() 时,您是否跟踪过您的提供程序中发生的情况?您可能还想发布您的提供者的删除方法。
  • 它在 ListView 上运行良好
  • 哦,我忘了在我的适配器上调用 notifydatasetchanged - 该项目确实被删除了,但是......它不是我点击的项目。当我尝试从组中删除最后一项时,它会从组中删除第一项。为什么?

标签: android contextmenu expandablelistview


【解决方案1】:

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

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

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

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

通过这个item,您应该能够轻松地获得数据库中的 id 或您需要的任何特定信息。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-04-01
    • 2014-07-17
    • 1970-01-01
    • 1970-01-01
    • 2019-06-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多