Android:如何找到从上下文菜单中单击的位置

时间:2010-03-16 10:41:26

标签: android android-emulator

我有一个填充数据的列表视图。我使用以下代码为listview设置了一个上下文菜单:

list.setOnCreateContextMenuListener
(
  new View.OnCreateContextMenuListener() 
  {
        public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) 
        {
       AdapterContextMenuInfo mi =(AdapterContextMenuInfo) menuInfo;
       menu.add(0, 0, 0, "Delete item");                
    }
   }
);

我有以下方法覆盖来控制选择的上下文菜单项:

@Override
public boolean onContextItemSelected(MenuItem item) 
{
  switch(item.getItemId()) 
  { 
  case 0: 
    ShowAlert("hello from delete item");
    break; 
  default: 
  return super.onContextItemSelected(item); 
  } 
  return true; 
}

在这个覆盖的方法中,我怎样才能找到被点击的列表视图的项目?

提前致谢。 最好的祝福。 何

3 个答案:

答案 0 :(得分:77)

您可以使用ContextMenu.ContextMenuInfo

类似的东西:

@Override
public boolean onContextItemSelected(MenuItem item) {
    AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
    int index = info.position;
}

您还可以获得正在显示菜单的确切View

@Override
public boolean onContextItemSelected(MenuItem item) {
    AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
    int index = info.position;
    View view = info.targetView;
}

答案 1 :(得分:3)

private static final int EDIT_ID = Menu.FIRST + 3;
private static final int DELETE_ID = Menu.FIRST + 4;
 @Override
    public void onCreateContextMenu(ContextMenu menu, View v,
            ContextMenu.ContextMenuInfo menuInfo) {
        menu.add(Menu.NONE, EDIT_ID, Menu.NONE, "Edit").setAlphabeticShortcut(
                'e');
        menu.add(Menu.NONE, DELETE_ID, Menu.NONE, "Delete")
                .setAlphabeticShortcut('d');
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item
                .getMenuInfo();
        switch (item.getItemId()) {
        case EDIT_ID:

            edit(info.id);
            return (true);
        case DELETE_ID:

            delete(info.id);
            return (true);
        }

        return (super.onOptionsItemSelected(item));
    }

答案 2 :(得分:0)

好的,解决问题信息null **** 使用静态成员并从持有者的位置设置值 要在longclick方法成员中保存值,例如: -

public class CurrentPosition {
   public static  int Pos{ get; set; }
}

public bool OnLongClick(View v)
{
    CurrentPosition.Pos = Position;
    return false;
}

并在您的上下文中使用选择项:

public override bool OnContextItemSelected(IMenuItem item)
{
    switch (item.ItemId)
    {
        case 0:
            return true;
        case 1:
            Toast.MakeText(this,CurrentPosition.Pos.ToString(), ToastLength.Long).Show();
            return true;
        case 2:
            Toast.MakeText(this, "Save", ToastLength.Long).Show();
            return true;
        }
        return true;
    }
}

C#代码