如何获取项目的位置点击ContextMenu?

时间:2012-09-14 12:42:54

标签: android nullpointerexception contextmenu

我正在使用此代码获取上下文菜单中的Clicked Item位置:

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

如此处所示:

Android: How to find the position clicked from the context menu

但我在第:

行得到NullPointerException
 int index = info.position;

为什么会这样?

修改

我有2个注册的contextMenu视图,如下所示:

button1.onClick(view v){
registerForContextMenu(v);
openContextMenu(v);
}

button2.onClick(view v){
registerForContextMenu(v);
openContextMenu(v);
}

然后根据v.getId()填充菜单。

2 个答案:

答案 0 :(得分:0)

答案 1 :(得分:0)

您可以直接使用:

EDITED BEGIN

@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
    AdapterView.AdapterContextMenuInfo info;
    try {
        info = (AdapterView.AdapterContextMenuInfo) menuInfo;
    } catch (ClassCastException e) {
        // If the menu object can't be cast, logs an error.
        Log.e("MENU", "bad menuInfo", e);
        return;
    }
    position = sectionAdapter.getIndexForPosition(info.position);
    menu.setHeaderTitle("");
    String[] menuItems = { "item1","item2","item3","item4" };
    for (int i = 0; i < menuItems.length; i++) {
        menu.add(Menu.NONE, i, i, menuItems[i]);
    }
}

已结束

public boolean onContextItemSelected(MenuItem item) {
    // TODO Auto-generated method stub
    int position = item.getItemId();
    switch (position) 
    {

        case 0:
        break;
        .
        .
        .
        default:
        break;
    }
}

希望它会对你有所帮助。