在ListItem ContextMenu中获取所选项目

时间:2012-06-24 07:11:14

标签: android android-listview android-contextmenu

我有一个ListView,可以长按其中一个元素创建一个ContextMenu。如何找到在创建此上下文菜单的ListView中选择的元素(而不是选定的MenuItem)?这是我的代码:

list.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {
    @Override
    public void onCreateContextMenu(ContextMenu menu, final View v,
            ContextMenuInfo menuInfo) {
        menu.setHeaderTitle("Actions");
        android.view.MenuItem remove = menu.add("Remove");
        final int selectedItem = ((ListView)v).getSelectedItemPosition();
        remove.setOnMenuItemClickListener(new OnMenuItemClickListener() {   
            @Override
            public boolean onMenuItemClick(android.view.MenuItem item) {
                doSomething(listAdapter.getItem(selectedItem)); // NPE here
                return true;
            }
        });
    }
});

请注意,我不想要从上下文菜单中选择的项目,而是需要触发此上下文菜单的ListView项目。

1 个答案:

答案 0 :(得分:8)

您需要AdapterContextMenuInfo

以下代码段将帮助您

public boolean onContextItemSelected(MenuItem item) {
      AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
      String[] names = getResources().getStringArray(R.array.names);
      switch(item.getItemId()) {
      case R.id.edit:
            Toast.makeText(this, "You have chosen the " + getResources().getString(R.string.edit) +
                        " context menu option for " + names[(int)info.id],
                        Toast.LENGTH_SHORT).show();
            return true;
      …………………..
      default:
            return super.onContextItemSelected(item);
      }