您好,我在从 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/