【问题标题】:How to delete an item from ExpandableListView on long click with a ContextMenuItemSelected?如何在长按 ContextMenuItemSelected 时从 ExpandableListView 中删除项目?
【发布时间】:2021-03-14 07:18:49
【问题描述】:

我正在尝试使用上下文菜单从 ExpandableListView 中删除一个项目。我遇到了空指针异常。请帮我解决这个问题。以下是我的代码:

@Override
public boolean onContextItemSelected(@NonNull MenuItem item) {
        super.onContextItemSelected(item);
        switch(item.getItemId())
        {
            case R.id.deleteItem:
                AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
                    int position = info.position;
                    //this is my ArrayList                    
                    postList.remove(position);
                    Toast.makeText(getActivity().getApplicationContext(), "Deleted an item", Toast.LENGTH_LONG).show();
                    listAdapter.notifyDataSetChanged();
                break;
            case R.id.editItem:
                break;
        }

        return true;
    }

【问题讨论】:

  • “我遇到空指针异常”然后检查 NPE。它说什么?尝试解决它!
  • item.getMenuInfo 返回 null,因为我使用的是自定义适配器。没有这个,我将无法知道列表视图中所选项目的位置。

标签: java android nullpointerexception expandablelistview android-contextmenu


【解决方案1】:

ContextMenuInfo 类型错误,Expandablelistview 中的项目有 2 个位置值,

    ExpandableListView.ExpandableListContextMenuInfo info = (ExpandableListView.ExpandableListContextMenuInfo) item.getMenuInfo();
    int groupPos = ExpandableListView.getPackedPositionGroup(info.packedPosition); 
    int childPos = ExpandableListView.getPackedPositionChild(info.packedPosition);

【讨论】:

  • 感谢您指出这个明显的错误!解决了问题
猜你喜欢
  • 2023-03-18
  • 1970-01-01
  • 2012-04-22
  • 1970-01-01
  • 1970-01-01
  • 2018-12-23
  • 2018-06-06
  • 2022-07-22
  • 1970-01-01
相关资源
最近更新 更多